当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ - Deprecated conversion from string constant to char

问题描述:

I don't understand why my compiler is giving me a warning about a deprecated conversion from string to char.

this is where is complaining about the warning:

Just a bit of background of what I'm doing.. I'm trying to understand and practice Exceptions... I'm not sure if its better to just work with char[1000] for the First name and so on.. I will really appreciate if someone help to understand the warning and help me to find a solution.. Thanks..

=================================================================================

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;

}

};

=====================Exception class=================================

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();}

};

网友答案:

I assume Exception's constructor signature is

Exception(int, char*)

You pass a string literal as a parameter, whose actual type is const char*, but the implicit conversion to char* is legal pre-C++11 (but deprecated, so you get the warning).

Modify the signature to

Exception(int, const char*)

or, better yet,

Exception(int, const std::string&)

To summarize:

char* x       = "stringLiteral";  //legal pre-C++11, deprecated
const char* y = "stringLiteral";  // good
std::string z  ("stringLiteral"); // even better
分享给朋友:
您可能感兴趣的文章:
随机阅读: