我有一個關於運算符重載的問題。以下是我的示例代碼。如果你可以通讀它並且我的問題在下面。爲什麼我的操作符重載處理左對象與右對象?
//class definition
class example
{
private:
int a ; // Defined in FeetInches.cpp
public:
void seta(int f)
{
a = f;
}
example operator + (const example &); // Overloaded +
int geta()
{
return a;
}
};
example example::operator + (const example &right)
{
example temp;
temp.a = a + right.a;
return temp;
}
//主
#include "header" //this is the class definition above
#include <iostream>
using namespace std;
int main()
{
example r;
r.seta(1);
example s;
s.seta(1);
example t;
t = r + s;
t = r + 1; //if included it won't compile
t = 1 + r; //if included it won't compile
int x = t.geta();
cout << x;
cin.get();
return 0;
}
我瞭解,當您嘗試添加到一起使用操作符重載,他們應該是相同的對象。
下面是問題: 我最近看到什麼時候該對象是在它編譯的操作符的一側,但是當它在另一側時它沒有。如:
t = r + 1;
它編譯。 t = 1 + r;
它沒有。
(另外我知道在我的例子這是行不通的任何一種方式,但只是更容易與框架代碼的問題。)
如何操作符重載時的對象是對操作的一面,但不能編譯當它在另一個上時編譯。
感謝
嘗試使用'運營商+'重寫你的任務:'r.operator +(1)' 。嘗試換一種方式,你會從編譯器的角度看到。 –
這就是爲什麼他們經常推薦將'operator + ='實現爲成員函數,然後將'operator +'實現爲全局函數。這樣隱式轉換可以發生在'+'運算符的左側或右側。 – Graznarak