你的代碼是這樣:
class Bag {
public:
Bag();
Bag(Bag const& other); // copy ctor, declared implicitly if you don't declare it
~Bag();
Bag operator+(Bag const& other) const;
private:
int x;
int y;
};
Bag Bag::operator+(Bag const& other) const {
Bag result (*this);
result.x += other.x;
result.y += other.y;
return result;
}
隱含的「當前對象」的成員函數指向名爲這的特殊值。然後*this
獲得該對象(通過取消引用這個),並且它用於構造(通過複製構造函數)另一個名爲的袋子結果。
我懷疑這個代碼是從一個家庭作業拍攝,所以你可能無法使用one true addition operator模式,但它是常見的,你應該知道的是:
struct Bag {
//...
Bag& operator+=(Bag const& other) {
x += other.x;
y += other.y;
return *this; // return a reference to the "current object"
// as almost all operator=, operator+=, etc. should do
}
};
Bag operator+(Bag a, Bag const& b) {
// notice a is passed by value, so it's a copy
a += b;
return a;
}
'operator +'函數是否缺少'return'語句? – 2010-03-28 06:40:17
這看起來不是有效的C++ - 新的是關鍵字 – Artyom 2010-03-28 08:08:25
如果你想創建操作符,我建議看'Boost.Operators'。他們將類似的操作符分組在一起(如'+ ='和'+'),並且只寫一個組給你其他人免費:) – 2010-03-28 14:10:11