重载运算符.Const论点会产生一些问题

overloading operator. Const arguments make some problems

本文关键字:问题 运算符 Const 重载      更新时间:2023-10-16
class Vector{
......
.......
private:
int dim;
public:
int getDim() {
return this->dim;

}
const Vector operator+(const  Vector& right){
this->getSize();
}
 };

我在这个->getSize((;中得到了编译错误;。它是由事实引起的,那个论点是正确的。我不知道哪里出了问题。我不想修改对。

假设您有一个非常量方法Vector::getSize()。您需要将其设为const,以便可以在const对象上或通过const引用或指向const的指针调用它。例如:

int getSize() const;
              ^^^^^

还要注意,返回const值没有多大意义(如果有移动语义,则会禁止它们(。加法成员运算符的规范形式是

// const method: A = B + C should not modify B
Vector operator+(const Vector& right) const;
                                      ^^^^^

和非成员

Vector operator+(const Vector& left, const Vector& right);