繁体   English   中英

运算符不应该是常数,但它可以

[英]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是否是个好主意。 很可能它甚至不是编译器允许它。 它只会混淆你班级的用户。

const方法使:

Matrix* _matrix;

指针常量下列方式:

Matrix* const _matrix;

不是那样的:

const Matrix* _matrix;

也就是说, 指针是const,而不是指针 因此,您可以在_matrix上调用非const方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM