2013-04-22 79 views
-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+() 
} 
+5

這是一個參考。任何[體面的入門C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)應該涵蓋這一點。 – 2013-04-22 09:24:33

+1

維基百科還爲初學者提供了不錯的信息:[運營商wiki](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators) – Dariusz 2013-04-22 09:26:27

回答

0

稱爲pass by reference,它是而不是特定於operator overloading。這是將參數傳遞給函數的一種方式[1.Pass by Copy,2.Pass by address,3.Pass by Reference]。使用C時,如果希望在函數中修改原始參數值時修改原始參數值,則可以使用pointers。但Cpp也提供pass by reference,名稱附加&行爲就像傳遞參數的替代名稱。 [也把你從所有非關聯化,並與指針相關聯的東西]

2
(const complx&) 
  1. 你是通過引用傳遞的價值。

  2. 引用只是原始對象的別名。

  3. 此處避免了額外的複製操作。 如果您已經使用'傳遞值'(如:(const complex)),則會爲形式參數調用複雜構造函數 。

希望這有助於延長。