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++的多态性必须有虚函数。切记!!!