我想通过重载+运算符来添加2个对象,但我的编译器说没有匹配函数来调用point :: point(int,int)。有人可以帮我解释这个代码,并解释错误吗?谢谢
#include <iostream>
using namespace std;
class point{
int x,y;
public:
point operator+ (point & first, point & second)
{
return point (first.x + second.x,first.y + second.y);
}
};
int main()
{
point lf (1,3)
point ls (4,5)
point el = lf + ls;
return 0;
}
您可以像这样更改代码,
#include <iostream>
using namespace std;
class point {
int x, y;
public:
point(int i, int j)
{
x = i;
y = j;
}
point operator+ (const point & first) const
{
return point(x + first.x, y + first.y);
}
};
int main()
{
point lf(1, 3);
point ls(4, 5);
point el = lf + ls;
return 0;
}
希望这可以帮助...
我得到的gdb错误是
main.cpp:8:49: error: ‘point point::operator+(point&, point&)’ must take either zero or one argument
这是因为您计划执行操作的对象是this
(左侧),然后右侧是参数。如果您希望使用您所采用的格式,那么您可以将声明放在课堂外 - 即
struct point
{
// note made into a struct to ensure that the below operator can access the variables.
// alternatively one could make the function a friend if that's your preference
int x,y;
};
point operator+ (const point & first, const point & second) {
// note these {} are c++11 onwards. if you don't use c++11 then
// feel free to provide your own constructor.
return point {first.x + second.x,first.y + second.y};
}
class point{
int x,y;
public:
point& operator+=(point const& rhs)& {
x+=rhs.x;
y+=rhs.y;
return *this;
}
friend point operator+(point lhs, point const& rhs){
lhs+=rhs;
return lhs;
}
};
上面有一堆小技巧,使这种模式成为一个很好的“没脑子”。