![](/img/trans.png)
[英]How to avoid deprecated conversion from string constant to 'char*' in C++
[英]C++ - Deprecated conversion from string constant to char
我不明白为什么我的编译器给我一个关于从字符串到char的弃用转换的警告。
这是抱怨警告的地方:
只是我正在做的一些背景...我正在尝试理解和练习例外...我不确定是否更好地使用char [1000]作为名字等等。如果有人帮助理解警告并帮助我找到解决方案,我将非常感激..谢谢..
================================================== ===============================
class TeLoEnYuco
{
string FN, LN, R;
double Income;
public:
const char *getters(){return FN.data(), LN.data(), R.data();}
virtual char *getFacilityAccess()=0;
TeLoEnYuco(char *fn, char *ln, char r, double inc)
{
if(fn==0) throw Exception(1, "First Name is Null"); //Warning #1
if(ln==0) throw Exception(2, "Last Name is Null"); //Warning #2
if(r==0) throw Exception(3, "Rank is Null"); //Warning #3
if(inc<=0) throw Exception(4, "Income is Null"); //Warning #4
FN=fn;
LN=ln;
R=r;
Income=inc;
}
};
=====================异常类=========================== ======
class Exception
{
int Code;
string Mess;
public:
Exception(int cd, char *mess)
{
Code=cd;
Mess=mess;
}
int getCode(){return Code;}
const char *getMess(){return Mess.data();}
};
我假设Exception
的构造函数签名是
Exception(int, char*)
您将字符串文字作为参数传递,其实际类型为const char*
,但隐式转换为char*
是合法的C ++之前的11(但不推荐使用,因此您会收到警告)。
将签名修改为
Exception(int, const char*)
或者,更好的是,
Exception(int, const std::string&)
总结一下:
char* x = "stringLiteral"; //legal pre-C++11, deprecated
const char* y = "stringLiteral"; // good
std::string z ("stringLiteral"); // even better
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.