首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C++中查找未知对象的类型

在C++中,查找未知对象的类型通常需要使用RTTI(Run-Time Type Information)技术。RTTI是C++的一个特性,允许在程序运行时获取对象的类型信息。以下是一个简单的示例,展示了如何使用RTTI在C++中查找未知对象的类型:

代码语言:cpp
复制
#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;
}

在这个示例中,我们定义了两个派生类Derived1Derived2,它们都继承自基类Base。我们使用typeid运算符获取对象的类型信息,并使用if-else语句进行比较。如果对象的类型与预期的类型匹配,则输出相应的信息。如果类型未知,则输出"Unknown object type"。

需要注意的是,为了使RTTI正常工作,基类应该声明一个虚析构函数。这是因为RTTI需要在运行时识别对象的动态类型,而虚析构函数是实现多态的关键。

总之,在C++中查找未知对象的类型可以使用RTTI技术,通过typeid运算符获取对象的类型信息,并使用if-else语句进行比较。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券