#include <iostream>
class Complex {
public:
double real;
double imag;
Complex(double r = 0, double i = 0) : real(r), 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,
real * other.imag + imag * other.real);
}
};
int main() {
Complex a(1, 2);
Complex b(3, 4);
Complex c(5, 6);
Complex result = (a + b) * c;
std::cout << "结果: " << result.real << " + " << result.imag << "i" << std::endl;
return 0;
}
- Complex类定义:
- 定义了
real
和imag
成员变量分别表示复数的实部和虚部。
- 提供了一个构造函数,默认实部和虚部为0,也可以传入实部和虚部的值。
- 运算符重载:
operator+
重载了加法运算符,返回两个复数相加后的结果。
operator*
重载了乘法运算符,按照复数乘法规则返回结果。
- 主函数:
- 创建了三个复数对象
a
、b
、c
。
- 通过重载后的运算符计算
(a + b) * c
,并输出结果。