sla*_*ais 3 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
};
Run Code Online (Sandbox Code Playgroud)
您需要将函数声明Get()为const:
const std::string Get() const { return s; }
Run Code Online (Sandbox Code Playgroud)
即使Get()不更改任何成员值,也会指示编译器仅允许您调用显式标记的函数const.
gcc通过使用参数指示您可以覆盖它的投诉-fpermissive; 但是,通常最好不要这样做(或者为什么要声明任何东西const?).通常,最好确保在const参数上调用的每个成员函数都是const成员函数.
这篇关于Const正确性的文章非常有趣.