【发布时间】:2011-05-09 01:42:37
【问题描述】:
可能重复:
What is the meaning of a const at end of a member function?
亲爱的,
我试图重载运算符 += 并且我得到了一些“丢弃限定符”的错误,只有通过在方法末尾添加“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总是一个好主意。 -
投票将其作为副本关闭。基本上,它在What is the meaning of a const at end of a member function? 中进行了解释(我现在将其标记为C++-FAQ,这样会更容易找到)。
标签: c++ class operator-overloading constants