设计一个程序,将加法运算符和减法运算符分别重载为成员函数,使之能够实现复数的加法运算与减法运算。将乘法运算符和除法运算符分别重载为友元函数,使之能够实现复数的乘法运算与除法运算
时间: 2024-02-05 11:13:43 浏览: 88
以下是一个可能的实现:
```c++
#include<iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0): real(r), imag(i) {}
Complex operator + (const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}
Complex operator - (const Complex& c) {
return Complex(real - c.real, imag - c.imag);
}
friend Complex operator * (const Complex& c1, const Complex& c2);
friend Complex operator / (const Complex& c1, const Complex& c2);
void display() {
cout << "(" << real << ", " << imag << ")" << endl;
}
};
Complex operator * (const Complex& c1, const Complex& c2) {
return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);
}
Complex operator / (const Complex& c1, const Complex& c2) {
double r = c2.real * c2.real + c2.imag * c2.imag;
return Complex((c1.real * c2.real + c1.imag * c2.imag) / r, (c1.imag * c2.real - c1.real * c2.imag) / r);
}
int main() {
Complex a(1.0, 2.0);
Complex b(3.0, 4.0);
Complex c = a + b;
c.display();
Complex d = a - b;
d.display();
Complex e = a * b;
e.display();
Complex f = a / b;
f.display();
return 0;
}
```
在上面的代码中,我们定义了一个名为 Complex 的类,表示复数。该类重载了加法运算符和减法运算符作为成员函数,重载了乘法运算符和除法运算符作为友元函数。在 main 函数中,我们创建了两个复数 a 和 b,并测试了加减乘除四种运算。
阅读全文