运算符重载允许自定义类型使用标准运算符,提升代码可读性;在C++中,可通过成员或友元函数重载算术运算符,如Complex类重载+、-、*、/等,实现复数运算,返回新对象且不修改原对象,复合赋值运算符如+=则修改自身并返回引用。

在面向对象编程中,运算符重载允许我们为自定义类型(如类或结构体)赋予标准运算符(如 +、-、*、/)新的行为。这样可以让对象像基本数据类型一样进行运算,使代码更直观、易读。
以 C++ 为例,实现算术运算符重载有以下常见方式:
下面定义一个简单的 Complex 类,表示复数,并重载 + 和 - 运算符:
#include <iostream>
using namespace std;
<p>class Complex {
private:
double real;
double imag;
public:
// 构造函数
Complex(double r = 0, double i = 0) : real(r), imag(i) {}</p><pre class='brush:php;toolbar:false;'>// 重载加法运算符(成员函数形式)
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 重载减法运算符(成员函数形式)
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
// 输出复数
void display() const {
cout << real << " + " << imag << "i" << endl;
}};
int main() { Complex c1(3, 4); Complex c2(1, 2); Complex c3 = c1 + c2; // 使用重载的 + Complex c4 = c1 - c2; // 使用重载的 -
cout << "c1 + c2 = "; c3.display(); cout << "c1 - c2 = "; c4.display(); return 0;
}
输出结果:
c1 + c2 = 4 + 6i类似地,你可以重载 *、/ 等运算符。例如重载乘法(复数乘法):
Complex operator*(const Complex& other) const {
// (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
return Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
);
}
也可以重载复合赋值运算符,如 +=:
Complex& operator+=(const Complex& other) {
real += other.real;
imag += other.imag;
return *this;
}
基本上就这些。通过运算符重载,我们可以让自定义类型参与直观的数学运算,提升代码可读性和可用性。
以上就是运算符重载如何实现 算术运算符重载示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号