获得有关一个对象运行时信息的方法
用typeid操作符来完成
操作符要返回一个type_info类的对象
该对象给出与其应用有关的对象的信息
//: C08:TypeInfo.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Illustrates the typeid operator.
#include <iostream>
#include <typeinfo>
using namespace std;
struct PolyBase { virtual ~PolyBase() {} };
struct PolyDer : PolyBase { PolyDer() {} };
struct NonPolyBase {};
struct NonPolyDer : NonPolyBase { NonPolyDer(int) {} };
int main() {
// Test polymorphic Types
const PolyDer pd;
const PolyBase* ppb = &pd;
cout << typeid(ppb).name() << endl;
cout << typeid(*ppb).name() << endl;
cout << boolalpha << (typeid(*ppb) == typeid(pd))
<< endl;
cout << (typeid(PolyDer) == typeid(const PolyDer))
<< endl;
// Test non-polymorphic Types
const NonPolyDer npd(1);
const NonPolyBase* nppb = &npd;
cout << typeid(nppb).name() << endl;
cout << typeid(*nppb).name() << endl;
cout << (typeid(*nppb) == typeid(npd)) << endl;
// Test a built-in type
int i;
cout << typeid(i).name() << endl;
getchar();
} ///:~
输出
struct PolyBase const *
struct PolyDer
true
true
struct NonPolyBase const *
struct NonPolyBase
false
int
因为ppb是一个指针
所以输出的第1行是它的静态类型
为了在程序中得到RTTI的结果
需要检查指针或引用目标对象
typeid应用到解析一个空指针的一个表达式hi引起一个bad_typeid异常
被抛出
type_info::name()返回哪个类名是完全限定的
//: C08:RTTIandNesting.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
#include <typeinfo>
using namespace std;
class One {
class Nested {};
Nested* n;
public:
One() : n(new Nested) {}
~One() { delete n; }
Nested* nested() { return n; }
};
int main() {
One o;
cout << typeid(*o.nested()).name() << endl;
getchar();
} ///:~
输出
class One::Nested
因为Nested是One类的一个成员类型
所以结果是One::Nested
在实现定义的 整理顺序 对文本的自然排序规则
可以用before询问一个对象是否在另一个type_info对象之前