为什么我会收到此代码的 -fallowive 错误
Why do I get an -fpermissive error with this code?
为什么编译器会在指示的行抱怨?
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
成员函数。
这篇关于常量正确性的文章非常有趣。
在你的operator =
对象内部,c
是一个常量对象:它具有const C
类型。在C++语言中,不允许调用常量对象的非常量成员函数。即调用c.Get()
是非法的,因为您的Get
是一个非常量成员函数。这就是编译器报告错误的原因。
要么使c
非常量(如注释掉的代码版本),要么使Get
常量。由您决定哪种方法是正确的,但看起来您应该采用后者。
作为旁注,将Get()
声明为返回const std::string
没有多大意义。如果您通过引用(如const std::string &
)返回它,那么该const
将是合适的。但是,由于您是按值返回的,因此将返回类型声明为 const
并不是那么有用。不过,这是您的个人风格问题。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 为什么我会收到此代码的 -fallowive 错误