设计一个程序,将加法运算符和减法运算符分别重载为成员函数,使之能够实现复数的加法运算与减法运算。将乘法运算符和除法运算符分别重载为友元函数,使之能够实现复数的乘法运算与除法运算
时间: 2024-02-05 12:13:06 浏览: 24
以下是一个可能的实现:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) {
real = r;
imag = i;
}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Complex operator-(Complex const &obj) {
Complex res;
res.real = real - obj.real;
res.imag = imag - obj.imag;
return res;
}
friend Complex operator*(Complex const &obj1, Complex const &obj2);
friend Complex operator/(Complex const &obj1, Complex const &obj2);
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
Complex operator*(Complex const &obj1, Complex const &obj2) {
Complex res;
res.real = obj1.real * obj2.real - obj1.imag * obj2.imag;
res.imag = obj1.real * obj2.imag + obj1.imag * obj2.real;
return res;
}
Complex operator/(Complex const &obj1, Complex const &obj2) {
Complex res;
double denominator = obj2.real * obj2.real + obj2.imag * obj2.imag;
res.real = (obj1.real * obj2.real + obj1.imag * obj2.imag) / denominator;
res.imag = (obj1.imag * obj2.real - obj1.real * obj2.imag) / denominator;
return res;
}
int main() {
Complex c1(3.0, 4.0), c2(-2.0, 5.0);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
Complex c6 = c1 / c2;
cout << "c1 = ";
c1.display();
cout << "c2 = ";
c2.display();
cout << "c1 + c2 = ";
c3.display();
cout << "c1 - c2 = ";
c4.display();
cout << "c1 * c2 = ";
c5.display();
cout << "c1 / c2 = ";
c6.display();
return 0;
}
```
在这个实现中,加法运算符和减法运算符被重载为成员函数,而乘法运算符和除法运算符被重载为友元函数。这个程序可以进行复数的加减乘除运算。