在运算符重载中使用"const"作为参数

Akk*_*rek 1 c++ const operator-overloading

我试图理解运算符重载,在我使用的教程中有一个重载"+"运算符的例子,用于添加两个对象.

  Box operator+(const Box& b)
  {
     Box box;
     box.length = this->length + b.length;
     box.breadth = this->breadth + b.breadth;
     box.height = this->height + b.height;
     return box;
  }
Run Code Online (Sandbox Code Playgroud)

为什么参数需要是对象的const引用?

Que*_*tin 10

该参数是const因为您不需要修改Box作为参数传递的参数.
方法本身也应该标记const,因为它也不会修改*this.