我有一个 Visual Studio 2008 C++03 项目,我想在其中验证对象是否属于某种类型。
例如:
int main()
{
struct A { virtual ~A() { }; };
struct B : public A { };
struct C : public A { };
A* b = new B();
A* c = new C();
assert( typeof( b ) == typeof( B ) );
assert( typeof( b ) != typeof( C ) );
assert( typeof( c ) == typeof( C ) );
assert( typeof( c ) != typeof( B ) );
assert( typeof( b ) != typeof( c ) );
return 0;
}
有没有办法在 C++03 中做到这一点?怎么办?
最佳答案
您可以使用 dynamic_cast
尝试将其转换为基础/派生类型。如果它不返回 NULL,那么它是一个基类或派生自该类型(取决于您是向上还是向下转换层次结构)
关于c++ - 验证基础对象是否属于特定的派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10705655/