此代码工作正常并打印"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 astd::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 astd::type_info
object representing the static type of the expression.
静态类型意味着类型是在编译时简单地确定的(对于
A*
,因此是 A
)。
关于c++ - 虚拟成员函数更改 typeid 的结果 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63754477/