运算符不应该是恒定的,但它可以是
operator shouldn't be constant but it can be
我实现了一个类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答案中的技巧。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 条件断点在不应该触发时触发
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我不应该把所有东西都放在标题中?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 找不到 QRegularExpression 行为的任何解释。它有效,但不应该
- 不允许运算符 const 参数调用 const 成员函数
- 在清除 istream 之前,我不应该需要取消获取它吗?
- 为什么 std::vector 使用 std::分配器而不是运算符 new 和 delete?
- c++ 为什么我不应该从不同的线程解锁互斥锁
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- "typename"不应该只在模板函数或模板类中使用吗?
- 在 c++ 中不使用 * 运算符将十进制值相乘
- 为什么 std::variant 找不到运算符<() 当与比较类不在同一命名空间中时
- 我应该使用运算符+=而不是运算符+来连接std::string吗?
- 后缀运算符不应该被视为二元运算符吗
- 运算符 [] 和 insert() 函数在 C++ 映射中的行为方式不应该相同吗?
- 运算符不应该是恒定的,但它可以是
- 为什么C++运算符 new/delete/variant 不应该出现在头文件中?
- 赋值运算符在不应该返回"empty"实例时返回?