我希望这段代码能够打印'Same 1' 和 'Same2',但它只打印'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";
}
Run Code Online (Sandbox Code Playgroud)
§5.2.8/ 2和§5.3.1/ 3似乎都向我建议应该打印'Same2'.
捕获的内容和位置是什么?
MSa*_*ers 17
指针不是多态类型.他们没有虚拟成员.事实上,他们没有任何成员.它们也不能从其他类型派生,也不能用作基类.因此,a的静态和动态类型T*总是如此T*.
在"Same2"行中,您要比较指针的typeid,而不是指向对象的typeid.因此编译器只查看静态类型C*和D*.它们显然不一样,必须有不同的type_info对象.
| 归档时间: |
|
| 查看次数: |
2134 次 |
| 最近记录: |