c++ - 虚拟成员函数更改 typeid 的结果 - 为什么?

标签 c++ inheritance typeid

此代码工作正常并打印"is":

#include <iostream>
using std::cout;
using std::endl;

class A {
public:
     virtual void talk() {  cout << "person talking" << endl;}
};

class B : public A {
public:
    void work() { cout << "employee working" << endl; }
};

int main() {
    A* pA = new B();

    if (typeid(*pA) == typeid(B))
        cout << "yes" << endl; // this is printed
    else
        cout << "no" << endl;
}
但如果我删除 virtual 关键字,它将打印“否”
#include <iostream>
using std::cout;
using std::endl;

class A {
public:
     void talk() {  cout << "person talking" << endl;}
};

class B : public A {
public:
    void work() { cout << "employee working" << endl; }
};

int main() {
    A* pA = new B();

    if (typeid(*pA) == typeid(B))
        cout << "yes" << endl;
    else
        cout << "no" << endl; // this is printed
}
为什么会这样?
为什么方法的虚拟性会影响对象的类型?
编辑:
为了让事情更困惑,这很好用:
((B*)(pA))->work(); // works fine, prints "employee working"
那么为什么 *pA 只被认为是 A 类对象(当没有 virtual 关键字时)但仍然可以调用 child 的 work() 方法?

最佳答案

就是这样typeid作品。没有虚拟成员的类是非多态类型并且不携带运行时类型信息。因此无法在运行时确定它的类型。
[expr.typeid]/p2 :

When typeid is applied to a glvalue expression whose type is a polymorphic class type, the result refers to a std​::​type_­info object representing the type of the most derived object (that is, the dynamic type) to which the glvalue refers.


[expr.typeid]/p3 :

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std​::​type_­info object representing the static type of the expression.


静态类型意味着类型是在编译时简单地确定的(对于 A*,因此是 A)。

关于c++ - 虚拟成员函数更改 typeid 的结果 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63754477/

相关文章:

c++ - 从 VS2005 或 VS2010 中的现有代码创建 C++ 项目

c++ - 如何在基类中初始化唯一变量(继承)

c++ - 多态类型的 typeid

c++ - 多态指针的typeid?

c++ - Eigen,如何处理按元素除以零

c++ - doxygen中的函数类型参数

PHP OOP 在子类中重新声明私有(private)方法/函数

c++ - 有没有办法在 C++ 中复合函数?

c++ - 预期等价物 : typeid of data expression and type expression

c++ - 如何在命令后保持我的 shell 运行