C++中运算符重载允许为类类型定义算术运算行为,示例中Complex类通过成员函数重载+、-、*、/实现复数计算,遵循不改变优先级、使用const引用参数等规则,并通过友元函数重载<<实现输出。

在C++中,运算符重载允许我们为自定义类型(如类或结构体)赋予标准运算符新的行为。算术运算符如 +、-、*、/ 等是最常被重载的运算符之一,用于实现对象之间的数学运算。
重载算术运算符需遵循以下规则:
以下是一个简单的复数类 Complex,演示如何重载 +、-、*、/ 运算符。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
using namespace std;
<p>class Complex {
private:
double real;
double imag;</p><p>public:
// 构造函数
Complex(double r = 0, double i = 0) : real(r), imag(i) {}</p><pre class='brush:php;toolbar:false;'>// 显示复数
void display() const {
cout << "(" << real << " + " << imag << "i)";
}
// 重载加法运算符(成员函数)
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);
}
// 重载乘法运算符
Complex operator*(const Complex& other) const {
// (a+bi)(c+di) = (ac-bd) + (ad+bc)i
double r = real * other.real - imag * other.imag;
double i = real * other.imag + imag * other.real;
return Complex(r, i);
}
// 重载除法运算符
Complex operator/(const Complex& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
if (denominator == 0) {
cerr << "除零错误!\n";
return Complex();
}
double r = (real * other.real + imag * other.imag) / denominator;
double i = (imag * other.real - real * other.imag) / denominator;
return Complex(r, i);
}
// 友元函数重载输出运算符
friend ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << " + " << c.imag << "i)";
return os;
}};
测试上面定义的运算符重载功能:
int main() {
Complex c1(3, 4); // 3 + 4i
Complex c2(1, 2); // 1 + 2i
<pre class='brush:php;toolbar:false;'>Complex sum = c1 + c2;
Complex diff = c1 - c2;
Complex prod = c1 * c2;
Complex quot = c1 / c2;
cout << "c1 = "; c1.display(); cout << endl;
cout << "c2 = "; c2.display(); cout << endl;
cout << "c1 + c2 = "; sum.display(); cout << endl;
cout << "c1 - c2 = "; diff.display(); cout << endl;
cout << "c1 * c2 = "; prod.display(); cout << endl;
cout << "c1 / c2 = "; quot.display(); cout << endl;
// 使用友元输出
cout << "使用重载<<: " << c1 << endl;
return 0;}
几点需要注意:
基本上就这些。掌握这些模式后,可以扩展到向量、矩阵、分数等类型的运算符重载。
以上就是C++运算符重载规则 算术运算符重载示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号