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

时间:2012-10-01 16:56:05

标签: c++ class testing

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

3 个答案:

答案 0 :(得分:2)

如果您的基类有一些虚拟成员(即它是多态的,我认为应该是这样的情况),您可以尝试down cast每个成员找出它的类型(即使用{{ 1}})。

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

答案 1 :(得分:0)

您可以使用dynamic_cast

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

答案 2 :(得分:0)

看一下这个例子:

#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 type\n";
    }
    else
    {
        cout << "a type is not equals to b type\n";
    }

    if (dynamic_cast<A *>(b) != NULL)
    {
        cout << "b is instance of A\n";
    }
    else
    {
        cout << "b is not instance of A\n";
    }

    if (dynamic_cast<B *>(a) != NULL)
    {
        cout << "a is instance of B\n";
    }
    else
    {
        cout << "a is not instance of B\n";
    }

    a = new B();

    if (typeid(a) == typeid(b))
    {
        cout << "a type equals to b type\n";
    }
    else
    {
        cout << "a type is not equals to b type\n";
    }

    if (dynamic_cast<B *>(a) != NULL)
    {
        cout << "a is instance of B\n";
    }
    else
    {
        cout << "a is not instance of B\n";
    }
}