c++ - 运算符不应该是常量,但可以是

标签 c++ class variables constants operator-keyword

我实现了一个类 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/

相关文章:

php - 在较新的 PHP 版本中使用具有相同 CSS 选择器名称的 PHP 变量的问题

javascript - 设置与自身相等的点有什么意义?

c++ - MSXML 内存泄漏

python - 在 Python 中覆盖

c++ - 继承,为什么要为基类调用两个构造函数,C++

php类在函数内调用函数

ios - 初始化 View Controller 时传递变量

C++:高层类层次结构

c++ - 开源 C++ 程序,接收 GPS (NMEA) 语句或 x,y 坐标并在 map 上播放位置

C++与类中的成员相同的类