码迷,mamicode.com
首页 > 其他好文 > 详细

自考新教材-p176_5(1)

时间:2020-02-08 12:00:18      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:class   复数   double   自考   include   nbsp   complex   public   put   

源程序:

#include <iostream>
#include <iomanip>
using namespace std;

class myComplex
{
private:
double real, imag;
public:
myComplex();
myComplex(double r,double i);
~myComplex() {};

friend myComplex operator+(const myComplex &c1, const myComplex &c2);
friend myComplex operator*(const myComplex &c1, const myComplex &c2);

void output();

};
myComplex::myComplex()
{
real = 0;
imag = 0;
}
myComplex::myComplex(double r, double i)
{
real = r;
imag = i;
}

myComplex operator+(const myComplex &c1, const myComplex &c2)
{
return myComplex(c1.real + c2.real, c1.imag + c2.imag);
}

myComplex operator*(const myComplex &c1, const myComplex &c2)
{
return myComplex(c1.real * c2.real-c1.imag*c2.imag, c1.imag*c2.real + c1.real*c2.imag);
}
void myComplex::output()
{
cout << real << setiosflags(ios::showpos)<<imag << "i" << endl;
}

int main()
{
myComplex c1(1, 2), c2(3, 4), res,res1;
res = c1 + c2;
res1 = c1 * c2;
cout << "两个复数相加,结果为:";
res.output();
cout << endl;
cout << "两个复数相乘,结果为:";
res1.output();
cout << endl;
system("pause");
return 1;
}

运行结果:

技术图片

 

自考新教材-p176_5(1)

标签:class   复数   double   自考   include   nbsp   complex   public   put   

原文地址:https://www.cnblogs.com/duanqibo/p/12275654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!