primer C++笔记
运行时类型识别
dynamic_cast运算符
指针类型的dynamic_cast
引用类型的dynamic_cast
typeid运算符
使用typeid运算符
//vs2017
//Base不含虚函数:
typeid(*bp) : class Base
typeid(*dp) : class Derived
typeid(bp) : class Base *
typeid(dp) : class Derived *
//Base含虚函数时:
typeid(*bp) : class Derived
typeid(*dp) : class Derived
typeid(bp) : class Base *
typeid(dp) : class Derived *
使用RTTI
class Base
{
friend bool operator==(const Base&, const Base&);
protected:
virtual bool equal(const Base&) const;
};
class Derived : public Base
{
protected:
virtual bool equal(const Base&) const;
};
//整体的相等运算符
bool operator==(const Base &lhs, const Base &rhs)
{
return typeid(lhs) == typeid(rhs) && lhs.equal(rhs);
}
bool Derived::equal(const Base & rhs) const
{
auto r = dynamic_cast<const Derived &>(rhs);
//执行比较Derived对象的操作
cout << "Derived::equal exec()" << endl;
}
bool Base::equal(const Base & rhs) const
{
//执行比较Base对象的操作
cout << "Base::equal exec()" << endl;
}
type_info类