typeid在VC中的使用

typeid在VC中使用会报如下警告,运行时会终止。

warning C4541: 'typeid' used on polymorphic type 'class A' with /GR-; unpredictable behavior may result

这是因为vc默认不支持RTTI导致的,解决方法如下:

在VC的project->project settings->c\c++中Category选择C++ Language,选中Enable Run-Time Type Information(RTTI),这样就可以正常使用了。


下面附下代码:

#include <iostream.h>
#include <string.h>
#include <typeinfo.h>

class A
{
public:
	A(char * p)
	{
		s = new char[strlen(p) + 1];
		strcpy(s, p);
		cout<<"A::A "<<s<<endl;
	}
	A(A& a)
	{
		if(this == &a)
		{
			return;
		}
		s = new char[strlen(a.s) + 1];
		strcpy(s, a.s);
		cout<<"A::A(A&a)"<<endl;
	}
	~A()
	{
		if(s)
			delete s;
		s = NULL;
		cout<<"A::~A"<<endl;
	}
	virtual void what(){cout<<s<<endl;}
	char *s;
};

class B: public A
{
public:
	B(char * p):A(p){cout<<"B::B"<<endl;}
	~B(){cout<<"B::~B"<<endl;}
};

void main()
{

	try
	{
		B a("abc");
		throw a;
	}
	catch (A & a)
	{
		cout<<typeid(a).name()<<endl;
	}

}

运行结果:

A::A abc
B::B
A::A(A&a)
B::~B
A::~A
class B
B::~B
A::~A
Press any key to continue


另外更正一些错误:

【如果throw的类中有字符串的话,否则会报一些警告,运行时还会死机。如果类中只有整型,是没问题的。】这句不对,只要派生类有虚函数,就会报警告,运行时也会死机。


【如果抛出的是基本类型是不会有警告的,包括整型,字符串等等。】这句也不对,警告warning C4541也是有的,但是执行不会报错。是对的,int和char *我都试过了。

代码如下:

#include <iostream.h>
#include <string.h>
#include <typeinfo.h>

class A
{
public:
	A(int i):data(i){}
	A(A& ra):data(ra.data){}
	 ~A(){}
	 virtual void what(){cout<<endl;}
	int data;
};

class B:public A
{
public:
	B(int i):A(i){}
	~B(){}

};

void main()
{
	try
	{
		//int i;
		char *p = "abc";
		throw p;
	}
	catch(A&ra)
	{
		cout<<typeid(ra).name()<<endl;
	}
	catch(int i)
	{
		cout<<typeid(i).name()<<endl;

	}
	catch(char*p)
	{
		cout<<typeid(p).name()<<endl;
	}
}

运行结果如下:

char *
Press any key to continue


一定要注意C++的多态性必须有虚函数。切记!!!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值