Possible duplicate:What is the meaning of a constant at the end of a member function?
Dear,
I tried to overload the + = operator, and I got some error "discard qualifiers", only adding "const" at the end of the method, I was able to get rid of the error. Can someone explain to me why this is necessary? Below is the code.
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); }
The method operator+=receives its argument as a reference to a constant, therefore it is not allowed to change the state of the received object.
operator+=
Therefore, through the const-reference (or const-pointer) you can:
const
mutable
, .
+= , *this, . const.
+=
*this
Vector &Vector::operator+=(const Vector &refVector);
, const ( ), const (refVector).
refVector
getLength refVector, const Vector &. const const.
getLength
const Vector &
operator+= refVector; const const, getLength() const.
getLength()
refVector.getLength(), refVector const Vector & refVector, getLength ok const.
refVector.getLength()
const Vector & refVector
operator+= const Vector&, getLength().
const Vector&
getLength() const, ( ) const.
const getLength(), , const.
refVector const Vector&, - const Vector.
Vector
const , this const objects.
this
operator+= refVector const. , , .
const , . , int getLength(); refVector refVector.getLength();. int getLength() const; . , .
int getLength();
refVector.getLength();
int getLength() const;
Source: https://habr.com/ru/post/1774518/More articles:TextBox.SelectAll () does not justify the text on the left in silverlight - c #Insert an XML string into an openXML document - c #How to resolve a subversion tree conflict: the branch deleted the directory, and the trunk changed the file there - svnMagenta pools in Zend Framework - phphttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1774517/tortoisesvn-approaches-to-resolve-tree-conflicts&usg=ALkJrhj0tFIt_JehX3BA2Ya4i_iyj4eHCACan I set the "isa" attribute of a Moose object attribute when building? - perlOverloading << and >> in inherited classes - c ++How to protect against SQL injection when a WHERE clause is dynamically created from a search form? - javaLib to protect SQL / javascript input for java / jsp - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1774523/create-report-with-pageviews-and-unique-visitors-using-gapi&usg=ALkJrhhWWC3XfbzCpIWlPuIngvjJ84Xh4gAll Articles