从0开始学C++ 第十七课:运算符重载
第十七课:运算符重载
学习目标:
- 理解运算符重载的概念和目的。
- 学习如何在类中重载运算符。
- 掌握重载不同运算符的基本规则。
学习内容:
-
运算符重载的概念:
- 运算符重载允许你为自定义数据类型重新定义操作符的行为,使得你可以对类的对象使用像
+
、-
、==
等标准运算符。
- 运算符重载允许你为自定义数据类型重新定义操作符的行为,使得你可以对类的对象使用像
-
如何在类中重载运算符:
- 运算符可以通过成员函数或全局函数重载。
- 一些运算符,如赋值(
=
),必须通过成员函数重载。
-
重载加法运算符的示例:
- 代码示例:
#include <iostream> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) : x(x1), y(y1) // 重载 '+' 运算符 Point operator+(const Point& p) { Point point(x + p.x, y + p.y); return point; } void display() { cout << "(" << x << ", " << y << ")" << endl; } }; int main() { Point p1(1, 2); Point p2(3, 4); Point p3 = p1 + p2; // 使用重载的 '+' 运算符 p3.display(); return 0; }
- 预计输出效果:
(4, 6)
- 使用场景: 运算符重载在创建数学类库(如复数类、矩阵类)或自定义数据类型(如大整数类)时非常有用,可以让这些自定义类型的操作更加直观和自然。
- 代码示例:
练习题: 编写一个类Vector2D
表示二维空间中的向量,为这个类重载加法(+
)和输出(<<
)运算符。加法运算符应返回两个向量的和,输出运算符应以(x, y)
的格式打印向量。
答案:
#include <iostream>
using namespace std;
class Vector2D {
private:
int x, y;
public:
Vector2D(int x1, int y1) : x(x1), y(y1) // 重载 '+' 运算符
Vector2D operator+(const Vector2D& v) {
return Vector2D(x + v.x, y + v.y);
}
// 重载 '<<' 运算符
friend ostream& operator<<(ostream& output, const Vector2D& v) {
output << "(" << v.x << ", " << v.y << ")";
return output;
}
};
int main() {
Vector2D v1(5, 4);
Vector2D v2(2, 3);
Vector2D v3 = v1 + v2;
cout << "v1 + v2 = " << v3 << endl;
return 0;
}
预计输出效果:
v1 + v2 = (7, 7)