2

我不明白为什么我的编译器会警告我从字符串到字符的不推荐转换。

这是抱怨警告的地方:

只是我正在做的一些背景..我正在尝试理解和练习异常...我不确定是否最好只使用 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();}
};
4

1 回答 1

14

我假设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
于 2013-07-31T20:15:14.240 回答