每当我尝试此代码来捕获类类型为异常,我会收到一条错误消息为“从字符串常量到'char *'不推荐使用的转换”。作为C++中的异常类类型中的错误
为什么是这样以及如何避免?
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class Error
{
int err_code;
char *err_desc;
public:
Error(int c , char* p)
{
err_code=c;
err_desc=new char(strlen(p));
strcpy(err_desc,p);
}
void display(void)
{
cout<<err_code<<"done successfully"<<err_desc;
}
};
int main()
{
int x;
try
{
cout<<"\n press any key to avoid exception except 99";
cin>>x;
if(x=99)
throw Error(x,"Exception");
}
catch (Error e)
{
cout<<"\n exception caught successfully";
e.display();
}
return 0;
}
...或更好,做正确的事情,并从std :: runtime_error派生 –