C++ 为什么此代码会出现 -fpermissive 错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11302412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get an -fpermissive error with this code?
提问by slashmais
Why would the compiler complain at the indicated line?
为什么编译器会在指定的行抱怨?
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
};
回答by user
You need to declare the function Get()
to be const
:
您需要将函数声明Get()
为const
:
const std::string Get() const { return s; }
Even though Get()
doesn't change any member values, the compiler is instructed to only let you call functions that are explicitly labeled const
.
即使Get()
不更改任何成员值,编译器也被指示只允许您调用显式标记为 的函数const
。
gcc is instructing you that you can override it's complaint by using the argument -fpermissive
; however, it's generally better not to do this (or else why declare anything const
at all?). Generally, it's better to make sure every member function called on a const
parameter is a const
member function.
gcc 指示您可以使用参数覆盖它的投诉-fpermissive
;但是,通常最好不要这样做(否则为什么要声明任何东西const
?)。通常,最好确保对const
参数调用的每个成员函数都是const
成员函数。
This article concerning Const Correctnessis very interesting.
这篇关于Const Correctness 的文章非常有趣。
回答by AnT
Inside your operator =
object c
is a constant object: it has const C
type. In C++ language you are not allowed to call non-constant member functions of constant objects. I.e. calling c.Get()
is illegal since your Get
is a non-constant member function. This is why the compiler reports an error.
在你的operator =
对象内部c
是一个常量对象:它有const C
类型。在 C++ 语言中,不允许调用常量对象的非常量成员函数。即调用c.Get()
是非法的,因为您Get
是一个非常量成员函数。这就是编译器报告错误的原因。
Either make your c
non-constant (as in your commented-out version of the code), or make Get
constant. It is up to you to decide which approach is right, but it looks like you should do the latter.
要么使您的c
非常数(如在代码的注释版本中),要么使您Get
保持不变。由您决定哪种方法是正确的,但看起来您应该选择后者。
As a side note, there's not much point of declaring Get()
as returning const std::string
. If you were returning it by reference (as const std::string &
) then that const
would be appropriate. But since you are returning by value, declaring the return type as const
is not that useful. It is a matter of your personal style though.
作为旁注,声明Get()
为 Return 并没有多大意义const std::string
。如果您通过引用返回它(作为const std::string &
),那么这const
将是合适的。但是由于您是按值返回,因此将返回类型声明const
为没有那么有用。不过这也是你个人风格的问题。