在C++中,查找未知对象的类型通常需要使用RTTI(Run-Time Type Information)技术。RTTI是C++的一个特性,允许在程序运行时获取对象的类型信息。以下是一个简单的示例,展示了如何使用RTTI在C++中查找未知对象的类型:
#include<iostream>
#include <typeinfo>
class Base {
public:
virtual ~Base() {}
};
class Derived1 : public Base {
};
class Derived2 : public Base {
};
int main() {
Base* pBase = new Derived1();
Base* pDerived2 = new Derived2();
try {
if (typeid(*pBase) == typeid(Derived1)) {
std::cout << "pBase points to an object of type Derived1"<< std::endl;
} else if (typeid(*pBase) == typeid(Derived2)) {
std::cout << "pBase points to an object of type Derived2"<< std::endl;
} else {
std::cout << "Unknown object type"<< std::endl;
}
if (typeid(*pDerived2) == typeid(Derived1)) {
std::cout << "pDerived2 points to an object of type Derived1"<< std::endl;
} else if (typeid(*pDerived2) == typeid(Derived2)) {
std::cout << "pDerived2 points to an object of type Derived2"<< std::endl;
} else {
std::cout << "Unknown object type"<< std::endl;
}
} catch (const std::bad_typeid& e) {
std::cerr << "Error: " << e.what()<< std::endl;
}
delete pBase;
delete pDerived2;
return 0;
}
在这个示例中,我们定义了两个派生类Derived1
和Derived2
,它们都继承自基类Base
。我们使用typeid
运算符获取对象的类型信息,并使用if-else
语句进行比较。如果对象的类型与预期的类型匹配,则输出相应的信息。如果类型未知,则输出"Unknown object type"。
需要注意的是,为了使RTTI正常工作,基类应该声明一个虚析构函数。这是因为RTTI需要在运行时识别对象的动态类型,而虚析构函数是实现多态的关键。
总之,在C++中查找未知对象的类型可以使用RTTI技术,通过typeid
运算符获取对象的类型信息,并使用if-else
语句进行比较。
领取专属 10元无门槛券
手把手带您无忧上云