-4

以下是运算符重载的示例代码。“&”在语法中是什么意思

complx operator+(const complx&) const; ?

#include <iostream>
using namespace std;
class complx
{
      double real,
             imag;
public:
      complx( double real = 0., double imag = 0.); // constructor
      complx operator+(const complx&) const;       // operator+()
};

// define constructor
complx::complx( double r, double i )
{
      real = r; imag = i;
}

// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
      complx result;
      result.real = (this->real + c.real);
      result.imag = (this->imag + c.imag);
      return result;

}

int main()
{
      complx x(4,4);
      complx y(6,6);
      complx z = x + y; // calls complx::operator+()
}
4

3 回答 3

2

这意味着您传递的是对变量的引用,而不是它的副本。

于 2013-04-22T09:24:10.273 回答
2
(const complx&)
  1. 您通过引用传递值。

  2. 引用只是原始对象的别名。

  3. 这里避免了额外的复制操作。如果您使用了像 : (const complex) 这样的“按值传递”,则为形参调用 complex 的复制构造函数。

希望这在一定程度上有所帮助。

于 2013-04-22T09:37:17.640 回答
0

这称为通过引用传递,它并不特定于operator overloading. 这是您将参数传递给函数的方法之一 [1.Pass by Copy, 2.Pass by address, 3.Pass by Reference]。当 您在函数中修改原始参数值时,您可以C使用它。pointersCpp也提供pass by reference,附加的名称&类似于传递参数的替代名称。[并且还使您免于所有与指针相关的取消引用和东西]

于 2013-04-22T09:32:07.570 回答