我正在學習C++,並創建了兩個簡單的hello-world應用程序。在他們兩人中,我使用操作員超載,但這是問題所在。在第一個,我可以提供兩個參數來重載運算符,並沒有問題。C++中運算符重載的參數個數
標題:
enum Element {a,b,c,d,e};
Element operator + (Element x, Element y);
//more overloads for -, *,/here
來源:
Element operator + (Element x, Element y) {
return ArrayOfElements[x][y];
}
但在我的第二應用(簡單的複數計算器) - 此方法不起作用。谷歌搜索,並弄清楚爲什麼後,我結束了這段代碼:
標題:
struct Complex {
double Re;
double Im;
Complex (double R, double I) : Re(R), Im(I) { }
Complex operator + (Complex &Number);
//more overloads
};
來源:
Complex Complex::operator + (Complex &Number)
{
Complex tmp = Complex(0, 0);
tmp.Re = Re + Number.Re;
tmp.Im = Im + Number.Im;
return tmp;
}
它的工作了,但我想知道,爲什麼在第一段代碼中,我被允許將兩個參數放在operator
重載中,但是第二個代碼中出現了以下錯誤?
complex.cpp:5:51: error: 'Complex Complex::operator+(Complex, Complex)' must take either zero or one argument
每當我使用類或不使用類時都是如此。我一直在尋找許多文檔,第二種方式似乎更加正確。也許這是因爲不同的參數類型?
使用g++
編譯的-Wall -pedantic
參數的兩個源都使用相同的庫。
成員函數有一個隱含的'this'參數 – 2013-03-15 20:43:48