你的代码是这样:
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