【问题标题】:disable assign integer to string c++禁用将整数分配给字符串c ++
【发布时间】:2017-11-27 09:43:49
【问题描述】:

std::string (std::basic_string) 有 'char' 类型的赋值运算符。 但是,出于这个原因, std::string 可以分配任何整数类型。 看小例子。

#include <string>
enum MyEnum{ Va = 0, Vb = 2, Vc = 4 };

int main(){
       std::string s;
       s = 'a'; // (1) OK - logical.
       s = Vc; //  (2) Ops. Compiled without any warnings.
       s = true; //  (3) Ops....
       s = 23;    // (4) Ops...
 }

问:如何禁用(或添加警告)(2、3、4)情况??

There is a related Question

【问题讨论】:

  • 为您的问题添加更多上下文,并在每个示例中包含所述编译器警告/错误。

标签: gcc c++03 g++4.8


【解决方案1】:

鉴于标签中的 C++03 和 GCC 4.8 的约束,我无法让 -Wconversion 做任何有用的事情(在 GCC 7 中,它甚至不会为我生成警告,尽管它告诉它我我正在使用--std=c++03)。

因此,有一个很好的实用解决方案,只需要在您的呼叫站点进行最少的更改:

通过一个类对象代理分配,该类对象包装您的字符串并允许从char 分配但不允许从int 分配:

#include <string>
enum MyEnum{ Va = 0, Vb = 2, Vc = 4 };

struct string_wr {
    string_wr (std::string& s) : val(s) {}
    operator std::string& () const { return val; }
    // we explicitly allow assigning chars.
    string_wr& operator= (char) { return *this; }

    // ww explicitly disable assigning ints by making the operator unreachable.
    private:
    string_wr& operator= (int);

    private:
    std::string& val;
};


int main(){
       std::string s;
       s = 'a'; // (1) OK - logical.
       s = Vc; //  (2) Ops. Compiled without any warnings.
       s = true; //  (3) Ops....
       s = 23;    // (4) Ops...

       string_wr m(s); // this is the only real change at the calling site
       m = 'a'; // (1) OK - logical.
       m = Vc; //  (2) Should fail with "assignment is private" kind of error.
       m = true; //  (3) Should fail...
       m = 23;    // (4) Should fail...

 }

但是,如果您的最终目标是在使用 std::string 时专门获得警告或错误,则 C++03 中的最佳选择是修补 &lt;string&gt; 标头以添加私有上面类中显示的 int 赋值运算符。但这意味着修补系统头文件,过程和结果将取决于您的编译器版本(并且必须在每个安装和编译器版本中重复)。

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2018-03-26
    • 2012-05-03
    相关资源
    最近更新 更多