求高手解答关于typeid的问题

ganmaojiushijiu 2012-08-06 12:03:39
#include<typeinfo>
#include<iostream>

using namespace std;

struct A{virtual ~A(){}};
struct B:A {};
struct C{};
struct D:C{D(int) {}};

int main()
{
B b;
A *a=&b;

cout<<typeid(b).name()<<endl;
cout<<typeid(*a).name()<<endl; //这里为什么输出的是struct B?
cout<<boolalpha<<(typeid(*a)==typeid(b))<<endl;
cout<<(typeid(A)==typeid(const A))<<endl;

D d(1);
C *c=&d;

cout<<typeid(d).name()<<endl;
cout<<typeid(*c).name()<<endl; //而这里为什么输出的是 struct C呢?
cout<<boolalpha<<(typeid(d)==typeid(*c))<<endl;
//cout<<(typeid(D)==typeid(const D))<<endl;

int i;

cout<<typeid(i).name()<<endl;

return 0;
}

问题已经在代码中问出求高手解答
...全文
75 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
iamnobody 2012-08-06
  • 打赏
  • 举报
回复
typeid
========
5.2.8 Type identification [expr.typeid]
2 When typeid is applied to an lvalue expression whose type is a polymorphic class type (10.3), the result
refers to a type_info object representing the type of the most derived object (1.8) (that is, the dynamic
type) to which the lvalue refers. If the lvalue expression is obtained by applying the unary * operator to a
pointer62) and the pointer is a null pointer value (4.10), the typeid expression throws the bad_typeid
exception (18.5.3).
Gloveing 2012-08-06
  • 打赏
  • 举报
回复
c++中,struct可以看做是特殊的class

这就是所谓的:虚函数,动态绑定 问题
titer1 2012-08-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

typeid
========
5.2.8 Type identification [expr.typeid]
2 When typeid is applied to an lvalue expression whose type is a polymorphic class type (10.3), the result
refers to a type_info object re……
[/Quote]

抓住英文解释中的the most derived object 。。
iamnobody 2012-08-06
  • 打赏
  • 举报
回复
简单说,多态类和非多态类是不一样的.

65,206

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧