您的位置:首页 > 其它

dynamic_cast与typeid关键字

2015-10-06 18:06 295 查看
C++的RTTI包含三部分内容:dynamic_cast, typeid和type_info(很少直接使用,但是需要了解一下,type_info的定义是由编译器定的,但是共同的是它包含一个name()函数)




dynamic_cast关键字的用法:

class Base1 {};
class Derive1: public Base1 {};
class Base2
{
public:
virtual void fun(void) {}
};
class Derive2: public Base2 {};
class Derive22:public Base2 {};

void main()
{
cout << typeid(1.1f).name() << endl;

Derive1 d1;
Base1 &b1 = d1;
cout << typeid(b1).name() << endl; //输出“class Base1”,因为Derive1和Base1之间没有多态性

Derive2 d2;
Base2 &b2 = d2;
cout << typeid(b2).name() << endl; //输出“class Derive2”,因为Derive1和Base1之间有了多态性

// 指针强制转化失败后可以比较指针是否为零,而引用却没办法,所以引用制转化失败后抛出异常
Derive2 *pb1 = dynamic_cast<Derive2 *>(&b2); // 输出"true",因为b2本身就确实是Derive2
cout << boolalpha << (0!=pb1) << endl;
Derive22 *pb2 = dynamic_cast<Derive22*>(&b2); //输出"false",因为b2本身不是Derive2
cout << boolalpha << (0 != pb2) << endl;

//引用转化
try
{
Derive2 &rb1 = dynamic_cast<Derive2&>(b2);//输出“true”,因为b2本身就是Derive2类型
cout << "true" << endl;
}
catch (bad_cast) //引用转化时,如果失败返回的是 bad_cast,指针转化失败返回的是 NULL(0),这是二者的不同之处
{
cout << "false" << endl;
}
try
{
Derive22 &rb2 = dynamic_cast<Derive22&>(b2); //b2本身是Derive2类型,不是Derive22类型
cout << "true" << endl;
}
catch (bad_cast)
{
cout << "false" << endl;
}
}



typeid关键字的用法:

class A
{
public:
virtual void func() {}
};

class B:public A
{
public:
void func() {}
};

void main()
{
A *pa;
B b, *pb;
pb = &b;
pa = pb;
cout << "Name1: " <<(typeid(pa).name()) << endl; //输出 class A
cout << "Name2: " <<(typeid(pb).name()) << endl; //输出 class B
cout << "*pa == *pb : " << (typeid(*pa).name() == typeid(*pb).name()) << endl; //二者相等,因为A中有虚函数

}



总结:

typeid(pa)返回的是指针类型。如果要返回对象的类型需要使用引用或者对象作为参数传递给typeid。

dynamic_cast是个运行时操作,但是它完全依赖虚函数表,如果某个两个类之间有继承关系,但是没有虚函数,那么dynamic_cast不能进行转化
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: