定义复数类,并在主函数定义类的对象进行调用测试。
要求:① 数据成员为双精度类型的实部和虚部。
② 具有无参和有参的构造函数。
③ 具有深拷贝构造函数。
④ 具有析构函数。
⑤ 具有输出函数、求模函数、加减乘除函数。
#include <iostream>
#include <math.h>
using namespace std;
class Complex
{
private:
double real;
double img;
public:
Complex() { real = img = 0.0; }
Complex(double r, double i) { real = r; img = i; }
Complex(const Complex &c) { real = c.real; img = c.img; }
~Complex() { cout << "dector has been called!" << endl; }
void Output() { cout << real << "+" << img << "i" << endl; }
Complex operator +(const Complex &c) { return Complex(real + c.real, img + c.img); }
Complex operator -(const Complex &c) { return Complex(real - c.real, img - c.img); }
Complex operator *(const Complex &c) { return Complex(real * c.real - img * c.img, img * c.real + real * c.img); }
Complex operator /(const Complex &c) { return Complex((real * c.real + img * c.img) / (c.real * c.real + c.img * c.img), (img * c.real - real * c.img) / (c.real * c.real + c.img * c.img)); }
double GetModulus() { return sqrt(img * img + real * real); }
};
int main()
{
Complex c1, c2(1.0, 2.0), c3(1.5, 2.5);
c1 = c2 + c3;
c1.Output();
Complex c4 = c1;
c4.Output();
cout << c4.GetModulus() << endl;
c4 = c2 - c3;
c4.Output();
c4 = c2 * c3;
c4.Output();
c4 = c2 / c3;
c4.Output();
return 0;
}