一、dynamic_cast运算符
dynamic_cast运算符是最常用的RTTI的组件,它不能回答“指针指向的是那类对象”这样的问题,
但能够回答“是否可以安全地将对象的地址赋给特定类型的指针”这样的问题。
class A {...};
class B :public A {...};
class C :public B {...};
B *p = dynamoc_cast<B *>(q);
//上述语句描述了指针q的类型是否可以安全的被转换为B*?如果可以,运算符将返回对象q的地址,否则返回一个空指针。
二、demon
#include<iostream>
#include<cstdlib>
#include<ctime>
using std::cout;
class A
{
private:
int hold;
public:
A(int h = 0) : hold(h){}
virtual void Speak() const { cout << "我是A类!\n"; }
virtual int Value() const { return hold; }
};
class B : public A
{
public:
B(int h = 0 ) : A(h) {}
void Speak() const { cout << "我是B类\n" ;}
virtual void Say() const
{
cout << "I hold the B value of " << Value() << "!\n";
}
};
class C : public B
{
private:
char ch;
public:
C(int h = 0,char c ='A') : B(h),ch(c){}
void Speak() const { cout << "我是C类\n"; }
void Say() const
{
cout << "i hold the character " << ch << "and the integer " <<Value() << "!\n";
}
};
A *GetOne();
int main()
{
std::srand(std::time(0));
A * pg;
B * ps;
for(int i = 0;i<5;i++)
{
pg = GetOne();
pg->Speak();
if(ps = dynamic_cast<B *>(pg))
{
ps->Say();
cout << "可以转换B类======" <<'\n';
}else
cout << "不可以转换" <<"\n";
cout <<"================I is "<< i << "\n\n";
}
return 0;
}
A *GetOne()
{
A *p;
switch(std::rand()%3)
{
case 0:
p = new A(std::rand()%100);
cout << "p是A类\n";
break;
case 1:
p = new B(std::rand()%100);
cout << "p是B类\n";
break;
case 2:
p = new C(std::rand()%100,'A'+std::rand()%26);
cout << "p是C类\n";
break;
}
return p;
}
运行结果: