[英]operator shouldn't be constant but it can be
我实现了一个MyMatrix类,它包含一个指向抽象类Matrix的指针(指针是_matrix)。 operator + =调用方法add并添加_matrix变量。 因此,作为类变量的_matrix被更改,因此+ =运算符不能是常量,但由于某种原因,编译器允许我将其设置为const,并且没有例外。 这是为什么?
const MyMatrix& MyMatrix::operator +=(const MyMatrix& other) const
{
_matrix->add(*other._matrix);
return *this;
}
这是添加:
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();
}
operator+=
允许为const,因为很可能你已经将_matrix
成员声明为一个简单的指针。 因此, operator+=
不会更改MyMatrix
的状态,因为您没有更改指针,而是指向的对象。
由你来决定将operator+=
声明为const是否是个好主意。 很可能它甚至不是编译器允许它。 它只会混淆你班级的用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.