C++中的RTTI机制详解(2)
在type_info类中,复制构造函数和赋值运算符都是私有的,同时也没有默认的构造函数;所以,我们没有办法创建type_info类的变量,例如type_info A;这样是错误的。那么typeid函数是如何返回一个type_info类的对象的引用的呢?我在这里不进行讨论,思路就是类的友元函数。
typeid函数的使用
typeid使用起来是非常简单的,常用的方式有以下两种:
1.使用type_info类中的name()函数返回对象的类型名称
就像上面的代码中使用的那样;但是,这里有一点需要注意,比如有以下代码:
#include <iostream>
#include <typeinfo>
using namespace std;
class A
{
public:
void Print() { cout<<"This is class A."<<endl; }
};
class B : public A
{
public:
void Print() { cout<<"This is class B."<<endl; }
};
int main()
{
A *pA = new B();
cout<<typeid(pA).name()<<endl; // class A *
cout<<typeid(*pA).name()<<endl; // class A
return 0;
}
我使用了两次typeid,但是两次的参数是不一样的;输出结果也是不一样的;当我指定为pA时,由于pA是一个A类型的指针,所以输出就为class A *;当我指定*pA时,它表示的是pA所指向的对象的类型,所以输出的是class A;所以需要区分typeid(*pA)和typeid(pA)的区别,它们两个不是同一个东西;但是,这里又有问题了,明明pA实际指向的是B,为什么得到的却是class A呢?我们在看下一段代码:
#include <iostream>
#include <typeinfo>
using namespace std;
class A
{
public:
virtual void Print() { cout<<"This is class A."<<endl; }
};
class B : public A
{
public:
void Print() { cout<<"This is class B."<<endl; }
};
int main()
{
A *pA = new B();
cout<<typeid(pA).name()<<endl; // class A *
cout<<typeid(*pA).name()<<endl; // class B
return 0;
}
好了,我将Print函数变成了虚函数,输出结果就不一样了,这说明什么?这就是RTTI在捣鬼了,当类中不存在虚函数时,typeid是编译时期的事情,也就是静态类型,就如上面的cout<<typeid(*pA).name()<<endl;输出class A一样;当类中存在虚函数时,typeid是运行时期的事情,也就是动态类型,就如上面的cout<<typeid(*pA).name()<<endl;输出class B一样,关于这一点,我们在实际编程中,经常会出错,一定要谨记。
2.使用type_info类中重载的==和!=比较两个对象的类型是否相等
这个会经常用到,通常用于比较两个带有虚函数的类的对象是否相等,例如以下代码:
#include <iostream>
#include <typeinfo>
using namespace std;
class A
{
public:
virtual void Print() { cout<<"This is class A."<<endl; }
};
class B : public A
{
public:
void Print() { cout<<"This is class B."<<endl; }
};
class C : public A
{
public:
void Print() { cout<<"This is class C."<<endl; }
};
void Handle(A *a)
{
if (typeid(*a) == typeid(A))
{
cout<<"I am a A truly."<<endl;
}
else if (typeid(*a) == typeid(B))
{
cout<<"I am a B truly."<<endl;
}
else if (typeid(*a) == typeid(C))
{
cout<<"I am a C truly."<<endl;
}
else
{
cout<<"I am alone."<<endl;
}
}
int main()
{
A *pA = new B();
Handle(pA);
delete pA;
pA = new C();
Handle(pA);
return 0;
}
这是一种用法,呆会我再总结如何使用dynamic_cast来实现同样的功能。
dynamic_cast的内幕
- 上一篇:C++单例模式应用实例
- 下一篇:C++设计模式之解释器模式