typeid---c++中该函数用于获知一个变量的具体类型

typeid

  c++中该函数用于获知一个变量的具体类型。   运行时获知变量类型名称,可以使用 typeid(变量).name,需要注意不是所有编译器都输出"int"、"float"等之类的名称,对于这类的编译器可以这样使用:float f = 1.1f; if( typeid(f) == typeid(0.0f) ) ……
详细请点击下面连接:
http://baike.baidu.com/view/1375171.htm
原文中有错误。测试:
// typeidtest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;

class Base1
{
};
class Derive1 :public Base1
{
};
//************
class Base2
{
 virtual void fun(void){}
};
class Derive2 :public Base2
{
};
//sample4 ************
class Derive22:public Base2
{
};
int _tmain(int argc, _TCHAR* argv[])
{
 cout << typeid(1.1f).name() << endl;
 Derive1* d11 = new Derive1;
 Base1* b11 = d11;
 cout <<typeid(*b11).name()<<endl;// 输出"class Base1",因为Derive1和Base1之间没有多态性
 Derive2 d21;
 Base2* b21 = &d21;
 cout<<typeid(*b21).name()<<endl;//输出"class Derive2",因为Derive1和Base1之间有了多态性
 Derive1 d1;
 Base1& b1 = d1;
 cout <<typeid(b1).name()<<endl;// 输出"class Base1",因为Derive1和Base1之间没有多态性
 
 Derive2 d2;
 Base2& b2 = d2;
 cout<<typeid(b2).name()<<endl;//输出"class Derive2",因为Derive1和Base1之间有了多态性
 Derive2* pb1 = dynamic_cast<Derive2*>(&b2);
 cout << boolalpha << (0!=pb1) << endl; // 输出"true",因为b2本身就确实是Derive2
 Derive22* pb2 = dynamic_cast<Derive22*>(&b2);
 cout << boolalpha << (0!=pb2) << endl; // 输出"false",因为b2本身不是Derive22
 
 try {                   // 输出"true"
  Derive2& rb1 = dynamic_cast<Derive2&>(b2);
  cout << "true" << endl;
 }
 catch( bad_cast ){
  cout << "false" << endl;
 }
 try {                     // 输出"false"
  Derive22& rb2 = dynamic_cast<Derive22&>(b2);
  cout << "true" << endl;
 }
 catch( ... ) // 应该是 bad_cast,但不知道为什么在VC++6.0中却不行
 {
  cout << "false" << endl;
 }
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值