目录
官方解析
博主栗子
官方解析
Run-Time Type Information解析
Run-time type information (RTTI)运行时类型信息是一个运行机制,这个机制是在程序执行期间要明确一个对象的类型。RTTI在C++中被使用的原因是许多类或者框架实现了很多功能,这就会造成类库间的不兼容。因此,RTTI解决了在语言层面上类库兼容问题。
RTTI几乎都是针对限制于指针问题。然而,讨论的概念也适用于引用。
RTTI在C++中主要的三种情况:
1.dynamic_cast操作符:使用多态类型的转换;
2.typeid操作符:用于识别这个类的具体类型;
3.type_info类:用于保护typeid这个操作符返回后的类型信息;
博主栗子
源码一:
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base print() called!\n";
}
};
class Child :public Base {
public:
void print() {
cout << "Child print() called!\n";
}
};
void main() {
Child *child = new Child;
child->print();
Base *base = dynamic_cast<Child*>(child);
//or use it in this way
//Base *base_2 = child;
base->print();
getchar();
}
运行截图如下:
源码二:
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
void print() {
cout << "Base print() called!\n";
}
};
class Child :public Base {
public:
void print() {
cout << "Child print() called!\n";
}
};
void main() {
cout << typeid(1).name() << endl;
cout << typeid(1.1).name() << endl;
cout << typeid(new Base).name() << endl;
cout << typeid(*new Base).name() << endl;
Child *child = new Child;
Base *base = child;
cout << typeid(base).name() << endl;
cout << typeid(*base).name() << endl;
getchar();
}
运行截图如下:
补充:typeid是在编译时期识别的,关于type_info将在以后的博文中给出
更多推荐
Micsorft文档阅读笔记-Run-Time Type Information解析及使用
发布评论