假设我有一个基类对象的向量,但使用它来包含许多派生类。我想检查该向量的成员是否属于特定类。我怎么做?我可以考虑制作一个派生类的模板,它接受基类的参数,但我不确定如何将类与对象进行比较。
答案 0 :(得分:2)
答案 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";
}
}