c++ - 为什么我会收到此代码的 -fpermissive 错误?

标签 c++ compiler-errors

为什么编译器会在指示的行报错?

class C
{
    std::string s;
public:
    C() { s = "<not set>";}
    ~C() {}
    void Set(const std::string ss) { s=ss; }
    const std::string Get() { return s; }

    C &operator=(const C &c) { Set(c.Get()); return *this; }
    //error: passing ‘const C’ as ‘this’ argument of ‘const string C::Get()’
    // discards qualifiers [-fpermissive]


    //C &operator=(C &c) { Set(c.Get()); return *this; }   <-- works fine

};

最佳答案

您需要将函数 Get() 声明为 const:

const std::string Get() const { return s; }

即使 Get() 不会更改任何成员值,编译器也会被指示只允许您调用显式标记为 const 的函数。

gcc 指示您可以使用参数 -fpermissive 覆盖它的投诉;然而,通常最好不要这样做(否则为什么要声明任何 const?)。通常,最好确保在 const 参数上调用的每个成员函数都是 const 成员函数。

这篇文章涉及Const Correctness很有趣。

关于c++ - 为什么我会收到此代码的 -fpermissive 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11302412/

相关文章:

iphone - 目标 IOS 3.1 的编译错误

android - 无论我做什么,Unity Android 构建在 Gradle 阶段都会失败

c++ - 当 header 中指定文本/纯文本时,eBay API 返回 JSON

c++ - std::thread 不是使用 Eclipse Kepler MinGW 命名空间 std 的成员

c++ - 创建自己的vector Class,错误很多

compiler-errors - “adadelta_solver”的Caffe编译错误

c++ - g++ 与 MSVC 中 C++ 引号的含义

c++ - 引用类型的数据成员提供 "loophole"围绕 const 正确性

compiler-errors - 我无法弄清楚这个 F# 错误消息

swift - 编译器不喜欢完成处理程序中的保护语句