gre*_*lip 2 c++ variables const class operator-keyword
我实现了一个MyMatrix类,它包含一个指向抽象类Matrix的指针(指针是_matrix).operator + =调用方法add并添加_matrix变量.因此,作为类变量的_matrix被更改,因此+ =运算符不能是常量,但由于某种原因,编译器允许我将其设置为const,并且没有例外.这是为什么?
const MyMatrix& MyMatrix::operator +=(const MyMatrix& other) const
{
_matrix->add(*other._matrix);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这是添加:
void add(Matrix &other)
{
for (int i = 0; i < other.getSize(); i++)
{
Pair indexPair = other.getCurrentIndex();
double value = other.getValue(indexPair);
pair<Pair, double> pairToAdd(indexPair, value);
other.next();
if (pairToAdd.second != 0)
{
setValue(pairToAdd.first, getValue(pairToAdd.first) + pairToAdd.second);
}
}
initializeIterator();
}
Run Code Online (Sandbox Code Playgroud)
operator+=
允许是const,因为很可能你已经将该_matrix
成员声明为一个简单的指针.因此,operator+=
不会更改状态,MyMatrix
因为您没有更改指针,而是指向的对象.
您可以决定operator+=
将const 声明为const 是一个好主意.很可能它甚至不是编译器允许它.它只会混淆你班级的用户.
该const
方法使:
Matrix* _matrix;
Run Code Online (Sandbox Code Playgroud)
指针常量以下列方式:
Matrix* const _matrix;
Run Code Online (Sandbox Code Playgroud)
不是那样的:
const Matrix* _matrix;
Run Code Online (Sandbox Code Playgroud)
也就是说,指针是const,而不是指针.因此,您可以调用非const方法_matrix
.
如果你想在const方法中强制指针的constness,请使用这个SO答案中的技巧.