C++加号运算符的重载
C++ overloading of the plus operator
我想通过重载 + 运算符来添加 2 个对象,但我的编译器说没有匹配的函数可以调用 point::p oint(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;
}
希望这有帮助...
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;
}
};
上面有一堆小技巧,使遵循这种模式成为一个很好的"不费吹灰之力"。
- 您可以通过"正确"的语义获得
+=
和+
。 - 如果将
+
链接在一起,则会省略左侧操作。 (即,a+b+c
变为(a+b)+c
,a+b
的返回值被省略到_+c
调用中(。 如果对象具有可移动状态,则无需设计成本即可进行正确的移动。 - 如果
a
或b
是point
,而另一个具有隐式转换为point
,则a+b
工作。 如果a
不是重点,则成员operator+
不这样做;这是毫无意义的不对称。 a+=b
实施通常比a=a+b
更有效。 当您在此处实现+=
时,您也会获得高效的+
。 而你的+=
又是根据成员变量+=
s 来定义的。
我得到的 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};
}
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用