gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:46:55 29 4
gpt4 key购买 nike

此代码工作正常并打印"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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com