运算符不应该是恒定的,但它可以是

operator shouldn't be constant but it can be

本文关键字:不应该 运算符      更新时间:2023-10-16

我实现了一个类MyMatrix,它保存了一个指向抽象类Matrix的指针(指针是_Matrix)。运算符+=调用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+=被允许为常量,因为很可能您已经将_matrix成员声明为简单指针。因此,operator+=不会更改MyMatrix的状态,因为您不是在更改指针,而是在更改指向的对象。

由您决定将operator+=声明为const是否是个好主意。即使编译器允许,也很可能不会。这只会混淆类的用户。

const方法使:

Matrix* _matrix;

指针常量,采用以下方式:

Matrix* const _matrix;

不是那样的:

const Matrix* _matrix;

也就是说,指针是常量,而不是指向对象。因此,您可以在_matrix上调用非常量方法。

如果您想在const方法中强制指针对象的const,请使用这个SO答案中的技巧。