目录
———————————————————————————————————————————
C++运算符重载是一种特殊的语法,允许我们为内置运算符或自定义类型的对象定义新的行为。通过运算符重载,我们可以使用相同的运算符对不同类型的对象进行不同的操作。
示例代码
以下是一个关于C++运算符重载的示例代码:
#include <iostream>
// 自定义类
class Point {
public:
int x;
int y;
Point(int x = 0, int y = 0): x(x), y(y) {}
// 运算符重载:+
Point operator+(const Point& other) {
Point result;
result.x = this->x + other.x;
result.y = this->y + other.y;
return result;
}
// 运算符重载:<<
friend std::ostream& operator<<(std::ostream& os, const Point& point) {
os << "(" << point.x << ", " << point.y << ")";
return os;
}
};
int main() {
Point p1(1, 2);
Point p2(3, 4);
Point sum = p1 + p2;
std::cout << "Sum: " << sum << std::endl;
return 0;
}
代码解析
在上面的代码中,我们定义了一个自定义类Point,并重载了+运算符和<<运算符。重载+运算符允许我们对Point对象执行加法运算,而重载<<运算符则用于自定义对象的输出。在main函数中,我们创建了两个点p1和p2,然后使用+运算符将它们相加,最后使用重载的<<运算符输出结果。
运行结果
运行以上代码的输出结果为:
Sum: (4, 6)
这就是C++中运算符重载的基本使用方法。当然,在实际应用中,我们可以根据需要重载其他的运算符,以实现更复杂的操作。
dingding提问解答