😊 C++ Operator重载的例子 🌟
在C++编程中,operator重载是一种强大的特性,可以让开发者自定义运算符的行为。例如,我们可以通过重载`+`运算符来实现两个对象相加的功能。下面是一个简单的例子:
假设我们有一个表示二维点的类 `Point`,我们希望可以直接用 `+` 运算符将两个点相加,得到一个新的点。代码如下:
```cpp
include
using namespace std;
class Point {
public:
int x, y;
Point(int a = 0, int b = 0) : x(a), y(b) {}
// 重载 + 运算符
Point operator+(const Point& other) const {
return Point(x + other.x, y + other.y);
}
void display() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(3, 4);
Point p2(1, 2);
Point p3 = p1 + p2; // 使用重载的 + 运算符
p3.display(); // 输出: (4, 6)
return 0;
}
```
通过这种方式,我们可以让代码更直观易读,同时提高复用性!🎉
Operator重载不仅限于算术运算符,还可以用于关系运算符、逻辑运算符等,是C++中非常实用的工具之一!✨
免责声明:本答案或内容为用户上传,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。 如遇侵权请及时联系本站删除。