【发布时间】:2010-11-11 04:16:57
【问题描述】:
当我第一次使用 GCC 4.3 编译我的 C++ 代码时(在使用 -Wall -Wextra 选项成功编译它并且在 4.1、4.0、3.4 上没有任何警告之后)我突然收到一堆 @ 形式的错误987654323@.
考虑temp.cpp:
class Something
{
public:
const int getConstThing() const {
return _cMyInt;
}
const int getNonconstThing() const {
return _myInt;
}
const int& getConstReference() const {
return _myInt;
}
int& getNonconstReference() {
return _myInt;
}
void setInt(const int newValue) {
_myInt = newValue;
}
Something() : _cMyInt( 3 ) {
_myInt = 2;
}
private:
const int _cMyInt;
int _myInt;
};
运行g++ temp.cpp -Wextra -c -o blah.o:
temp.cpp:4: warning: type qualifiers ignored on function return type
temp.cpp:7: warning: type qualifiers ignored on function return type
谁能告诉我我做错了什么违反了 C++ 标准?我想当按值返回时,前导 const 是多余的,但我无法理解为什么需要用它生成警告。还有其他地方我应该去掉 const 吗?
【问题讨论】:
-
查看类似的问题和答案:stackoverflow.com/questions/1607188/…
-
我以前看到过这样的警告,不过,我花了几分钟试图了解我的代码中发生了什么。可能更好的错误报告会加快速度。而不是
warning: type qualifiers ignored on function return type之类的warning: please don't add const qualifier when you are returning by value。 -
@Avio 为什么我们不应该将
const限定符添加到返回值的函数中?我们这样做是因为我们不希望该值之后能够更改。 -
@Franky const int foo();
标签: c++ constants gcc-warning