c++重载运算符复数
时间: 2023-06-21 17:12:43 浏览: 103
运算符重载
在 C++ 中,可以通过重载运算符来定义复数类型的加法、减法、乘法和除法等运算。以下是一个示例代码:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex operator*(const Complex& c) const {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex operator/(const Complex& c) const {
double denominator = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << "+" << c.imag << "i";
return os;
}
};
int main() {
Complex c1(1, 2), c2(2, 3);
cout << "c1=" << c1 << endl;
cout << "c2=" << c2 << endl;
cout << "c1+c2=" << c1 + c2 << endl;
cout << "c1-c2=" << c1 - c2 << endl;
cout << "c1*c2=" << c1 * c2 << endl;
cout << "c1/c2=" << c1 / c2 << endl;
return 0;
}
```
在上述代码中,我们定义了一个名为 Complex 的类,用于表示复数。该类包含了两个私有成员变量 real 和 imag,分别表示实部和虚部。我们重载了加法运算符 operator+、减法运算符 operator-、乘法运算符 operator* 和除法运算符 operator/,并且实现了一个友元函数 operator<<,用于输出复数类型。
在主函数中,我们创建了两个复数对象 c1 和 c2,然后进行加、减、乘、除等运算,并输出结果。
阅读全文