gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:05:48 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com