天天看点

C++笔记 19.2 运行时类型识别primer C++笔记

primer C++笔记

运行时类型识别

C++笔记 19.2 运行时类型识别primer C++笔记

dynamic_cast运算符

C++笔记 19.2 运行时类型识别primer C++笔记

指针类型的dynamic_cast

C++笔记 19.2 运行时类型识别primer C++笔记

引用类型的dynamic_cast

C++笔记 19.2 运行时类型识别primer C++笔记

typeid运算符

C++笔记 19.2 运行时类型识别primer C++笔记

使用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 *
           
C++笔记 19.2 运行时类型识别primer C++笔记
C++笔记 19.2 运行时类型识别primer C++笔记
C++笔记 19.2 运行时类型识别primer C++笔记

使用RTTI

C++笔记 19.2 运行时类型识别primer C++笔记
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类

C++笔记 19.2 运行时类型识别primer C++笔记
C++笔记 19.2 运行时类型识别primer C++笔记
C++笔记 19.2 运行时类型识别primer C++笔记