如何在C++中检查对象的类?

How can I check an object's class in C++?

本文关键字:对象 检查 C++      更新时间:2023-10-16

假设我有一个基类的对象向量,但用它来包含许多派生类。我想检查该向量的成员是否属于特定类。我该怎么做?我可以考虑制作一个派生类的模板,该模板接受基类的参数,但我不确定如何将类与对象进行比较。

如果你的基类有一些虚拟成员(即它是多态的,因为我认为它应该在这种情况下),你可以尝试向下投射每个成员以找出它的类型(即使用 dynamic_cast )。

否则,您可以使用RTTI(即 typeid)。

您可以使用dynamic_cast

但是如果你需要这样做,那么你可能有一个设计问题。 你应该使用多态性或模板来解决这个问题。

看看这个例子:

#include <iostream>
using namespace std;
#include <typeinfo>
class A
{
public:
    virtual ~A()
    {
    }
};
class B : public A
{
public:
    virtual ~B()
    {
    }
};
void main()
{
    A *a = new A();
    B *b = new B();
    if (typeid(a) == typeid(b))
    {
        cout << "a type equals to b typen";
    }
    else
    {
        cout << "a type is not equals to b typen";
    }
    if (dynamic_cast<A *>(b) != NULL)
    {
        cout << "b is instance of An";
    }
    else
    {
        cout << "b is not instance of An";
    }
    if (dynamic_cast<B *>(a) != NULL)
    {
        cout << "a is instance of Bn";
    }
    else
    {
        cout << "a is not instance of Bn";
    }
    a = new B();
    if (typeid(a) == typeid(b))
    {
        cout << "a type equals to b typen";
    }
    else
    {
        cout << "a type is not equals to b typen";
    }
    if (dynamic_cast<B *>(a) != NULL)
    {
        cout << "a is instance of Bn";
    }
    else
    {
        cout << "a is not instance of Bn";
    }
}