当我首次使用GCC 4.3编译我的C++代码时(在使用-Wall -Wextra
选项成功编译过4.1、4.0和3.4版本后),我突然遇到了很多形如warning: type qualifiers ignored on function return type
的错误。
考虑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
吗?
const
限定符?这是因为我们不希望该值在之后被更改。 - Franky