#include <iostream>
#include <typeinfo>
class Base {
public:
virtual ~Base() {} // 必须有虚函数,RTTI 才能工作
};
class Derived : public Base {
public:
void show() {
std::cout << "Derived class" << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
// 使用 typeid 检查类型
if (typeid(*basePtr) == typeid(Derived)) {
std::cout << "basePtr points to a Derived object" << std::endl;
} else {
std::cout << "basePtr does not point to a Derived object" << std::endl;
}
// 使用 dynamic_cast 安全地向下转型
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr != nullptr) {
derivedPtr->show();
} else {
std::cout << "basePtr does not point to a Derived object" << std::endl;
}
delete basePtr;
return 0;
}
typeid
和 dynamic_cast
。typeid
运算符:用于获取对象的类型信息。它可以用来比较两个对象是否属于同一类型。dynamic_cast
:用于安全地进行基类指针到派生类指针的转换。如果转换失败,dynamic_cast
返回 nullptr
。以上代码展示了如何使用 RTTI 来检查和转换指针类型。
上一篇:c++ #if
下一篇:c++ map排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站