1. 类的定义,构造函数,成员函数 2.两个复数运算的运算符重载.重载 +、-、*、/、++、--、<<、>>等运算符 3. double型数可以转换成复数
时间: 2023-07-10 12:38:33 浏览: 116
好的,我会记住您的要求,下面是回答您的问题:
1. 类的定义:
```cpp
class Complex{
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0):real(r), imag(i){} //构造函数
Complex(const Complex& c){real = c.real; imag = c.imag;} //复制构造函数
Complex& operator=(const Complex& c){real = c.real; imag = c.imag; return *this;} //赋值运算符重载
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); //除法运算符重载
}
Complex& operator++(){ //前置++运算符重载
++real;
return *this;
}
Complex operator++(int){ //后置++运算符重载
Complex c(*this);
real++;
return c;
}
Complex& operator--(){ //前置--运算符重载
--real;
return *this;
}
Complex operator--(int){ //后置--运算符重载
Complex c(*this);
real--;
return c;
}
friend istream& operator>>(istream& in, Complex& c){ //输入运算符重载
in >> c.real >> c.imag;
return in;
}
friend ostream& operator<<(ostream& out, const Complex& c){ //输出运算符重载
out << c.real << "+" << c.imag << "i";
return out;
}
operator double(){return real;} //double型转换成复数运算符重载
};
```
2. 复数运算符重载:
```cpp
Complex operator+(const Complex& c1, const Complex& c2){return c1 + c2;}
Complex operator-(const Complex& c1, const Complex& c2){return c1 - c2;}
Complex operator*(const Complex& c1, const Complex& c2){return c1 * c2;}
Complex operator/(const Complex& c1, const Complex& c2){return c1 / c2;}
Complex& operator++(Complex& c){return ++c;}
Complex operator++(Complex& c, int){return c++;}
Complex& operator--(Complex& c){return --c;}
Complex operator--(Complex& c, int){return c--;}
ostream& operator<<(ostream& out, const Complex& c){out << c; return out;}
istream& operator>>(istream& in, Complex& c){in >> c; return in;}
```
3. double型转换成复数:
```cpp
Complex(double r = 0.0, double i = 0.0):real(r), imag(i){}
Complex(double r):real(r), imag(0){}
```
以上是对您的问题的回答,希望能够帮到您!
阅读全文