今天我注意到了一些東西。如果我創建三個版本的重載+運算符來處理每一個組合(對象+原始,原始+對象,對象+對象)一切都按預期執行:C++重載我的重載操作符?
class Int
{ int data;
public:
Int(){data = 0; };
Int (int size){ data = size; };
friend int operator+(Int, Int);
friend int operator+(int, Int);
friend int operator+(Int, int);
};
int operator+(Int lInt, Int rInt)
{ cout <<"first version. ";
return rInt.data + lInt.data;
}
int operator+(int lInt, Int rInt)
{ cout <<"second version. ";
return rInt.data + lInt;
}
int operator+(Int lInt, int rInt)
{ cout <<"third version. ";
return lInt.data + rInt;
}
int main(int argc, char *argv[]) {
Int int1 = 1;
cout << int1 + int1 <<endl; // prints "first version. 2"
cout << 3 + int1 << endl; // prints "second version. 4"
cout << int1 + 3 << endl; // prints "third version. 4"
}
但如果我刪除第二和第三個版本中,它仍作品!?!
class Int
{ int data;
public:
Int(){data = 0; };
Int (int size){ data = size; };
friend int operator+(Int, Int);
};
int operator+(Int lInt, Int rInt)
{ cout <<"first version. ";
return rInt.data + lInt.data;
}
int main(int argc, char *argv[]) {
Int int1 = 1;
cout << int1 + int1 <<endl; // prints "first version. 2"
cout << 3 + int1 << endl; // prints "first version. 4"
cout << int1 + 3 << endl; // prints "first version. 4"
}
如何爲我的重載+運營商,這意味着接受兩個對象,能夠採取一個int和對象。它如何能夠採取對象和int?我希望我不會在這裏忽略一些顯而易見的東西!
也感謝你。現在我明白了! – 2015-04-04 20:14:22
不客氣:) – bgoldst 2015-04-04 20:15:32