可能重复:
What is the meaning of a const at end of a member function?运算符+ =重载,为什么是const?
亲爱的朋友们,
我试图使用操作符重载+ =和我得到的 “丢弃预选赛” 的一些错误,只能通过在方法的末尾添加“const”,我能够摆脱错误。有人可以解释为什么这是必要的吗?下面,代码。
class Vector{
public:
Vector();
Vector(int);
//int getLength();
int getLength() const;
const Vector & operator += (const Vector &);
~Vector();
private:
int m_nLength;
int * m_pData;
};
/*int Vector::getLength(){
return (this->m_nLength);
}*/
int Vector::getLength() const{
return (this->m_nLength);
}
const Vector & Vector::operator += (const Vector & refVector){
int newLength = this->getLength() + refVector.getLenth();
...
...
return (*this);
}
请注意,如果不需要更改状态,则使成员函数为'const'总是一个好主意。 – 2010-11-12 13:11:17
投票将其作为副本关闭。基本上,它在[成员函数结束时的const是什么意思?](http://stackoverflow.com/questions/4059932/what-is-the-meaning-of-a-const-at - 成员函数的终结)(我现在标记为[C++ - FAQ](http://stackoverflow.com/questions/tagged/c%2b%2b-faq),所以它会更容易找到)。 – sbi 2010-11-12 13:21:08
感谢您的建议! – Javier 2010-11-12 13:28:20