RTTI(Run-Time Type Information,通过运行时类型信息)程序能够使用基类的指针或者引用来检查这些指针或引用所指的对象的实际派生类对象。
#include<iostream>
using namespace std;
class A
{
private:
int num;
};
class B:public A
{
private:
int num;
};
void main()
{
A *pa = new A;
A *pb = new B;
cout << "*pa: " << typeid(*pa).name()<< " *pb: "<<typeid(*pb).name() << endl;
cout << "pa: " << typeid(pa).name ()<< " pb: " << typeid(pb).name() << endl;
cin.get();
}可以看出typeid解析出*pa和*pb 都为class A
#include<iostream>
using namespace std;
class A
{
private:
int num;
virtual void go()
{
}
};
class B:public A
{
private:
int num;
void go()
{
}
};
void main()
{
A *pa = new A;
A *pb = new B;
cout << "*pa: " << typeid(*pa).name()<< " *pb: "<<typeid(*pb).name() << endl;
cout << "pa: " << typeid(pa).name ()<< " pb: " << typeid(pb).name() << endl;
cin.get();
}
从这可以看出,虚函数可以确定数据类型。
#include<iostream>
using namespace std;
class A
{
private:
int num;
virtual void go()
{
}
};
class B:public A
{
private:
int num;
void go()
{
}
};
void main()
{
A *pa = new A;
A *pb = new B;
B *pb1 = dynamic_cast<B*>(pa);
B *pb2 = dynamic_cast<B*>(pb);
if (pb1 == nullptr)
{
cout << "pa转换失败" << endl;//由于pa指向的A的对象但是其中并没有B的对象实体,在安全情况下其返回为空。
}
if (pb2 == nullptr)
{
cout << "pb转换失败" << endl;
}
cin.get();
}版权声明:欢迎转载,如有不足之处,恳请斧正。
原文:http://blog.csdn.net/huangshanchun/article/details/46807535