野百合也有春天

导航

在运行时确定对象的类型

#include "stdafx.h"

#include <iostream>
#include <typeinfo>

using namespace std;

class Base {};
class Derived : public Base {};

int main( ) {

	Base b, bb;
	Derived d;

	// Use typeid to test type equality
	if (typeid(b) == typeid(d)) { // No
		cout << "b and d are of the same type.\n";
	}
	if (typeid(b) == typeid(bb)) { // Yes
		cout << "b and bb are of the same type.\n";
	}
	if (typeid(d) == typeid(Derived)) { // Yes
		cout << "d is of type Derived.\n";
		cout<<typeid(d).name()<<endl;
	}
}

posted on 2010-09-04 13:35  flydream  阅读(226)  评论(0编辑  收藏  举报