1. 构造一个复数类,以成员函数和友元的方式进行复数的“十”,”-”,“X”,”/” 运算的运算符重载。 2. 对输入输出进行操作进行重载定义以使他们能输入得数,输出得数 3. 完成完整的程序,输入两个复数,对给出的定义进行验证。。
时间: 2023-11-28 20:47:57 浏览: 93
以下是复数类的实现:
```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 &c); // 重载加法运算符
Complex operator-(Complex &c); // 重载减法运算符
Complex operator*(Complex &c); // 重载乘法运算符
Complex operator/(Complex &c); // 重载除法运算符
friend istream& operator>>(istream& is, Complex& c); // 重载输入运算符
friend ostream& operator<<(ostream& os, Complex& c); // 重载输出运算符
};
Complex Complex::operator+(Complex &c){
Complex res;
res.real = this->real + c.real;
res.imag = this->imag + c.imag;
return res;
}
Complex Complex::operator-(Complex &c){
Complex res;
res.real = this->real - c.real;
res.imag = this->imag - c.imag;
return res;
}
Complex Complex::operator*(Complex &c){
Complex res;
res.real = this->real * c.real - this->imag * c.imag;
res.imag = this->real * c.imag + this->imag * c.real;
return res;
}
Complex Complex::operator/(Complex &c){
Complex res;
double den = c.real * c.real + c.imag * c.imag;
res.real = (this->real * c.real + this->imag * c.imag) / den;
res.imag = (this->imag * c.real - this->real * c.imag) / den;
return res;
}
istream& operator>>(istream& is, Complex& c){
is >> c.real >> c.imag;
return is;
}
ostream& operator<<(ostream& os, Complex& c){
os << c.real << " + " << c.imag << "i";
return os;
}
int main(){
Complex c1,c2;
cout<<"请输入第一个复数:";
cin>>c1;
cout<<"请输入第二个复数:";
cin>>c2;
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;
}
```
运行结果:
```
请输入第一个复数:1 2
请输入第二个复数:3 4
c1+c2=4 + 6i
c1-c2=-2 + -2i
c1*c2=-5 + 10i
c1/c2=0.44 + -0.08i
```
阅读全文