“&”是什么表示运算符重载

时间:2013-04-22 09:22:42

标签: c++

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

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+()
}

3 个答案:

答案 0 :(得分:2)

这意味着您将reference传递给变量,而不是它的副本。

答案 1 :(得分:2)

(const complx&)
  1. 您正在通过引用传递值。

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

  3. 此处避免了额外的复制操作。 如果您使用了'pass by value',如:(const complex),那么复制构造函数 对于形式参数调用complex。

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

答案 2 :(得分:0)

这称为pass by reference 特定于operator overloading。这是将参数传递给函数的方法之一[1.Pass by Copy,2.Pass by address,3.Pass by Reference]。使用C时,如果希望在函数中修改原始参数值时修改原始参数值,则可以使用pointers。但Cpp也提供pass by reference,附加&的名称就像传递参数的替代名称。 [并且还可以避免所有解除引用和与指针相关的内容]

相关问题