嗨我想爲+(加法)操作符來添加我的用戶定義的數據類型對象的操作符重載。 以下是該代碼。如何添加標準和用戶定義的對象?
#include <iostream>
using namespace std;
class complex {
int i;
double f;
public:
complex(int ii=0,double ff=0){
i = ii;
f = ff;
}
complex operator+(complex object) {
complex result;
result.i = this->i + object.i;
result.f = this->f + object.f;
return result;
}
void display() {
cout << i <<"\t"<< f;
cout << endl;
}
};
int main(){
complex obj1(1,1.1),obj2(2,2.2),obj3;
int i(5);
obj3 = obj1 + obj2;
obj3.display();
obj3 = obj3 + i;
obj3.display();
obj3 = i + obj3;//generates me compiler error
obj3.display();
return 0;
}
據我瞭解,當我做OBJ1 + obj2的,它是由編譯器爲obj1.operator擴張+(OBJ2); 因此,這部分代碼工作正常。
但是,當我做添加一個int和複雜的,我認爲它擴展爲i.operator(obj1)。
因此,它給我編譯錯誤。
我應該在int類中定義operator +函數還是如何解決這個問題? 請建議, 謝謝
我建議你閱讀關於什麼運營商通常可以做什麼,應該做什麼,實現爲免費功能的地方。 – PlasmaHH 2012-01-16 11:07:41