检查c++ 11中的对象类型

Checking the object type in C++11

本文关键字:对象 类型 c++ 检查      更新时间:2023-10-16

我有一个继承自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中的对象类型?

有些类是多态的,有些是非多态的。

一个多态类有一个或多个虚函数(可能继承),一个非多态类没有虚函数。

你的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_casttypeid的最派生对象(以及虚函数调度)。

非多态类没有这些信息,因此它们只能报告编译时已知的静态类型。非多态类比多态类更紧凑、更高效。这就是为什么不是所有的c++类都是多态的。这种语言让程序员在性能和功能之间做出权衡。例如:

struct X { int x; };
struct Y : X {};
struct Z : Y {};

在我的系统中,非多态Zsizeof(Z) == 4 bytes,与int相同。

struct X { int x; virtual ~X() {}; };
struct Y : X {};
struct Z : Y {};

现在使Z多态性后,sizeof(Z) == 16 bytes。因此,Z的数组现在要大300%,因为每个Z实例必须在运行时存储其类型信息。