我实现了一个类 MyMatrix,它包含一个指向抽象类 Matrix 的指针(指针是 _matrix)。 运算符 += 调用方法 add 并添加 _matrix 变量。 因此,作为类变量的 _matrix 被更改,因此 += 运算符不能是常量, 但出于某种原因,编译器允许我将其设置为 const,并且没有异常(exception)。 这是为什么?
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 是否是一个好主意由您决定。即使编译器允许,也很可能不是。它只会让您类(class)的用户感到困惑。
关于c++ - 运算符不应该是常量,但可以是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661310/