当前位置:首页  科技

科技

😊 C++ Operator重载的例子 🌟

2025-03-16 00:19:29
导读 在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++中非常实用的工具之一!✨

免责声明:本文由用户上传,如有侵权请联系删除!