[英]operator shouldn't be constant but it can be
I implemented a class MyMatrix that holds a pointer to an abstract class Matrix (the pointer is _matrix). 我实现了一个MyMatrix类,它包含一个指向抽象类Matrix的指针(指针是_matrix)。 the operator += calls the method add and adds the _matrix variables. operator + =调用方法add并添加_matrix变量。 therefore, _matrix which is a class variable is changed, thus the += operator CANNOT be constant, but for some reason the compiler allows me to set it as const, and there are no exceptions. 因此,作为类变量的_matrix被更改,因此+ =运算符不能是常量,但由于某种原因,编译器允许我将其设置为const,并且没有例外。 why is that? 这是为什么?
const MyMatrix& MyMatrix::operator +=(const MyMatrix& other) const
{
_matrix->add(*other._matrix);
return *this;
}
this is add: 这是添加:
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+=
is allowed to be const because most probably you have declared the _matrix
member as a simple pointer. operator+=
允许为const,因为很可能你已经将_matrix
成员声明为一个简单的指针。 Therefore, operator+=
does not change the state of MyMatrix
because you are not changing the pointer, but the object pointed to. 因此, operator+=
不会更改MyMatrix
的状态,因为您没有更改指针,而是指向的对象。
It is up to you to decide whether it is a good idea to declare operator+=
as const. 由你来决定将operator+=
声明为const是否是个好主意。 Most probably it is not even if the compiler allows it. 很可能它甚至不是编译器允许它。 It will only confuse the users of your class. 它只会混淆你班级的用户。
The const
method makes the: const
方法使:
Matrix* _matrix;
pointer constant in the following manner: 指针常量以下列方式:
Matrix* const _matrix;
not in that way: 不是那样的:
const Matrix* _matrix;
That is, the pointer is const, not the pointee . 也就是说, 指针是const,而不是指针 。 Hence, you can call non-const methods on _matrix
. 因此,您可以在_matrix
上调用非const方法。
If you want to force constness of a pointee in a const method, use the trick from this SO answer. 如果你想在const方法中强制指针的constness,请使用这个SO答案中的技巧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.