问题描述
我希望此代码打印Same 1和Same2,但只打印Same1:
I expected this code to print 'Same 1' and 'Same2', but it prints only 'Same1':
#include <iostream>
#include <typeinfo>
using namespace std;
struct C{virtual ~C(){}};
struct D : C{};
int main(){
D d;
C c, &cr1 = d;
if(typeid(cr1) == typeid(D)) cout << "Same1";
if(typeid(&cr1) == typeid(D*)) cout << "Same2";
}
两者都是5.2.8 / 2和5.3.1 / 3似乎建议我打印'Same2'。
Both §5.2.8/2 and §5.3.1/3 seem to suggest to me that 'Same2' should be printed.
捕获什么和在哪里?
推荐答案
指针不是多态型。他们没有虚拟成员。事实上,他们没有成员。它们也不能从其他类型派生,也不能用作基类。因此, T *
的静态和动态类型总是 T *
。
Pointers aren't polymorphic types. They don't have virtual members. In fact, they have no members whatsoever. They also cannot derive from other types, nor be used as base classes. Hence, the static and dynamic type of a T*
is always T*
.
在Same2行中,您要比较指针的typeid,而不是指向的对象。因此,编译器仅查看静态类型 C *
和 D *
。它们显然不一样,必须有不同的 type_info
对象。
In your "Same2" line, you're comparing the typeid of a pointer, not the pointed-to object. The compiler therefore only looks at the static types C*
and D*
. They're obviously not the same, and must have distinct type_info
objects.
这篇关于多态类型的typeid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!