2018-11-15 05:13

C++类与对象 怎样利用复数类算复数的模等运算？

② 具有无参和有参的构造函数。
③ 具有深拷贝构造函数。
④ 具有析构函数。
⑤ 具有输出函数、求模函数、加减乘除函数。

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

1条回答

• ``````#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;
}
``````
点赞 评论 复制链接分享