标签:c++对象模型 rtti实现原理 typeid dynamic_cast
RTTI是Runtime Type Identification的缩写,意思是运行时类型识别。C++引入这个机制是为了让程序在运行时能根据基类的指针或引用来获得该指针或引用所指的对象的实际类型。但是现在RTTI的类型识别已经不限于此了,它还能通过typeid操作符识别出所有的基本类型(int,指针等)的变量对应的类型。class type_info
{
public:
virtual ~type_info();
bool operator==(const type_info&)const;
bool operator!=(const type_info&)const;
bool before(const type_info&)const;
const char* name()const;
private:
type_info(const type_info&);
type_info& operator=(const type_info&);
// data members
};class X { ...... // 具有virtual函数 };
class XX : public X { ...... // 具有virtual函数};
class Y { ...... // 没有virtual函数};
int main()
{
int n = 0;
XX xx;
Y y;
Y *py = &y;
// int和XX都是类型名
cout << typeid(int).name() << endl;
cout << typeid(XX).name() << endl;
// n为基本变量
cout << typeid(n).name() << endl;
// xx所属的类虽然存在virtual,但是xx为一个具体的对象
cout << typeid(xx).name() << endl;
// py为一个指针,属于基本类型
cout << typeid(py).name() << endl;
// py指向的Y的对象,但是类Y不存在virtual函数
cout << typeid(*py).name() << endl;
return 0;
}class X
{
public:
X()
{
mX = 101;
}
virtual void vfunc()
{
cout << "X::vfunc()" << endl;
}
private:
int mX;
};
class XX : public X
{
public:
XX():
X()
{
mXX = 1001;
}
virtual void vfunc()
{
cout << "XX::vfunc()" << endl;
}
private:
int mXX;
};void printTypeInfo(const X *px)
{
cout << "typeid(px) -> " << typeid(px).name() << endl;
cout << "typeid(*px) -> " << typeid(*px).name() << endl;
}
int main()
{
X x;
XX xx;
printTypeInfo(&x);
printTypeInfo(&xx);
return 0;
}
typedef void (*FuncPtr)();
int main()
{
XX xx;
FuncPtr func;
char *p = (char*)&xx;
// 获得虚函数表的地址
int **vtbl = (int**)*(int**)p;
// 输出虚函数表的地址,即vptr的值
cout << vtbl << endl;
// 获得type_info对象的指针,并调用其name成员函数
cout << "\t[-1]: " << (vtbl[-1]) << " -> "
<< ((type_info*)(vtbl[-1]))->name() << endl;
// 调用第一个virtual函数
cout << "\t[0]: " << vtbl[0] << " -> ";
func = (FuncPtr)vtbl[0];
func();
// 输出基类的成员变量的值
p += sizeof(int**);
cout << *(int*)p << endl;
// 输出派生类的成员变量的值
p += sizeof(int);
cout << *(int*)p << endl;
return 0;
}

class X
{
public:
X()
{
mX = 101;
}
private:
int mX;
};
class XX : public X
{
public:
XX():
X()
{
mXX = 1001;
}
private:
int mXX;
};void printTypeInfo(const X *px)
{
cout << "typeid(px) -> " << typeid(px).name() << endl;
cout << "typeid(*px) -> " << typeid(*px).name() << endl;
}
int main()
{
X x;
XX xx;
printTypeInfo(&x);
printTypeInfo(&xx); // 注释1
return 0;
}
class X
{
public:
X()
{
mX = 101;
}
virtual ~X()
{
}
private:
int mX;
};
class XX : public X
{
public:
XX():
X()
{
mXX = 1001;
}
virtual ~XX()
{
}
private:
int mXX;
};
class YX : public X
{
public:
YX()
{
mYX = 1002;
}
virtual ~YX()
{
}
private:
int mYX;
};int main()
{
X x;
XX xx;
YX yx;
X *px = &xx;
cout << px << endl;
XX *pxx = dynamic_cast<XX*>(px); // 转换1
cout << pxx << endl;
YX *pyx = dynamic_cast<YX*>(px); // 转换2
cout << pyx << endl;
pyx = (YX*)px; // 转换3
cout << pyx << endl;
pyx = static_cast<YX*>(px); // 转换4
cout << pyx << endl;
return 0;
}
标签:c++对象模型 rtti实现原理 typeid dynamic_cast
原文地址:http://blog.csdn.net/ljianhui/article/details/46487951