C++ 运算符和参数
假设我有一个类 Point:
class Point {
int x, y;
public:
Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; }
};
为什么我不能这样称呼它:
Point p1;
p1 += Point(10,10);
有什么方法可以做到这一点,同时仍然有一个引用作为参数?
Let's say I have a class Point:
class Point {
int x, y;
public:
Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; }
};
Why can I not call this as such:
Point p1;
p1 += Point(10,10);
And is there any way to do this, while still having a reference as the argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为你忘记声明一个匹配的构造函数。 除此之外,这个调用看起来不错。
(此外,
operator +=
中的代码是错误的:它会覆盖值而不是进行添加)。Because you forgot to declare a matching constructor. Other than that, this call looks fine.
(Also, the code inside your
operator +=
is wrong: it overwrites the values instead of doing additions).这是您需要的代码:
正如 Konrad 指出的,您需要一个构造函数。 此外,您还需要在运算符重载中显式执行添加操作。
Here's the code you need:
As Konrad pointed out, you need a constructor. Also you need to explicitly perform the additions inside your operator overload.
你的操作员代码完全没问题。 您需要创建一个采用两个整数的构造函数:
请注意,如果您声明一个采用一些参数的构造函数,那么为了进行实例化,例如
Point x;
,您需要自己声明一个默认构造函数。PS 只需阅读康拉德的回答。 是的,您可能希望为您的成员使用
+=
而不是=
。 :)You operator code is perfectly fine. You need to create a constructor which takes two ints:
Note that if you declare a constructor which takes some arguments then in order to make instantiation such as
Point x;
you need to declare a default constructor yourself.P.S. Just read Konrad's answer. Yes, you might want to use
+=
rather than=
for your members. :)