要求定义一个复数类,利用运算符重载定义该复数类的加法减法,取反运算。注意双目运算使用友元方式,单目使用成员方式另外使用转换函数实现该类对double类型的相互转化。并在主函数main中输出
时间: 2024-03-27 07:38:05 浏览: 80
复数类加减法运算符重载成员函数
5星 · 资源好评率100%
好的,以下是复数类的定义和运算符重载的实现:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
friend Complex operator+(const Complex& a, const Complex& b);
friend Complex operator-(const Complex& a, const Complex& b);
Complex operator-() const;
operator double() const { return real; }
void print() const {
if (imag < 0)
cout << real << "-" << -imag << "i" << endl;
else
cout << real << "+" << imag << "i" << endl;
}
};
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.real - b.real, a.imag - b.imag);
}
Complex Complex::operator-() const {
return Complex(-real, -imag);
}
int main() {
Complex a(2, 3), b(3, -4);
(a + b).print();
(a - b).print();
(-a).print();
double x = 1.23;
Complex c = x;
c.print();
return 0;
}
```
运行结果:
```
5-i
-1+7i
-2-3i
1.23+0i
```
阅读全文