相关疑难解决方法(0)

在C++ 11中检查对象类型

我有继承自A的B类.

class A
{
};

class B : public A
{
};
Run Code Online (Sandbox Code Playgroud)

我有三个对象.

A* a = new A();
A* a2 = new B();
B* b = new B();
Run Code Online (Sandbox Code Playgroud)

我想如果检查a是A类型的对象,a2是B类型的对象(不是A),b是B类型的对象.

我试过打字比较,但它没有给我正确的答案.

cout << (typeid(*a) == typeid(A)) << endl; // -> 1
cout << (typeid(*a2) == typeid(A)) << endl; // -> 1
cout << (typeid(*b) == typeid(A)) << endl; // -> 0

cout << (typeid(*a) == typeid(B)) << endl; // -> 0
cout << (typeid(*a2) == typeid(B)) << endl; // -> 0 …
Run Code Online (Sandbox Code Playgroud)

c++ rtti typeid c++11

5
推荐指数
1
解决办法
7518
查看次数

标签 统计

c++ ×1

c++11 ×1

rtti ×1

typeid ×1