我有一个继承自A的类B。
class A
{
};
class B : public A
{
};我有三个对象。
A* a = new A();
A* a2 = new B();
B* b = new B();我想知道,如果检查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
cout << (typeid(*b) == typeid(B)) << endl; // -> 1我尝试了动态转换,但是我得到了编译错误。
B* derived = dynamic_cast<B*>(a);
if (derived) {
cout << "a is B";
}
derived = dynamic_cast<B*>(a2);
if (derived) {
cout << "a2 is B";
}
derived = dynamic_cast<B*>(b);
if (derived) {
cout << "b is B";
}
typename.cpp: In function 'int main(int, char**)':
typename.cpp:27:36: error: cannot dynamic_cast 'a' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
B* derived = dynamic_cast<B*>(a);
^
typename.cpp:31:34: error: cannot dynamic_cast 'a2' (of type 'class A*') to type 'class B*' (source type is not polymorphic)
derived = dynamic_cast<B*>(a2);我使用静态类型转换,但我得到了错误的答案。
B* derived = static_cast<B*>(a);
if (derived) {
cout << "a is B"; // -> YES
}
derived = static_cast<B*>(a2);
if (derived) {
cout << "a2 is B"; // -> YES
}
derived = dynamic_cast<B*>(b);
if (derived) {
cout << "b is B"; // -> YES
}如何正确识别C++11中的对象类型
发布于 2013-06-20 10:59:52
有些类是多态的,有些是非多态的。
多态类有一个或多个虚函数(可能是继承的),非多态类有零个虚函数。
您的A和B是非多态的。
A和B的多态版本将展示您想要的行为:
#include <iostream>
#include <typeinfo>
using namespace std;
struct A
{
virtual ~A() {}; // add virtual function
};
class B : public A
{
};
A* a = new A();
A* a2 = new B();
B* b = new B();
int main()
{
cout << (typeid(*a) == typeid(A)) << endl; // -> 1
cout << (typeid(*a2) == typeid(A)) << endl; // -> 0 <-- CHANGED
cout << (typeid(*b) == typeid(A)) << endl; // -> 0
cout << (typeid(*a) == typeid(B)) << endl; // -> 0
cout << (typeid(*a2) == typeid(B)) << endl; // -> 1 <-- CHANGED
cout << (typeid(*b) == typeid(B)) << endl; // -> 1
}多态类的实例在运行时存储其最派生对象的动态类型。
(在您的示例中,a2是指向A的指针类型,并且指向类型A的对象,但是该对象只是B类型的最受驱动的对象的基类子对象。当查询a2时,您想要获得的是这个派生最多的对象B的类型。为此,您需要一个多态类。)
这就是多态类如何支持派生最多的对象的dynamic_cast和typeid (以及虚拟函数分派)。
非多态类没有此信息,因此它们只能报告编译时已知的静态类型。与多态类相比,非多态类更加紧凑和高效。这就是为什么不是所有的C++类都是多态的。该语言让程序员在性能和功能之间进行权衡。例如:
struct X { int x; };
struct Y : X {};
struct Z : Y {};在我的系统上,非多态Z是sizeof(Z) == 4 bytes,与int相同。
struct X { int x; virtual ~X() {}; };
struct Y : X {};
struct Z : Y {};现在,在使Z多态之后,sizeof(Z) == 16 bytes。因此,Z数组现在大了300%,因为每个Z实例都必须在运行时存储其类型信息。
https://stackoverflow.com/questions/17204487
复制相似问题