C++ 编写复数类Complex。
答案:1 悬赏:10 手机版
解决时间 2021-04-02 05:56
- 提问者网友:动次大次蹦擦擦
- 2021-04-01 18:44
C++ 编写复数类Complex。
最佳答案
- 五星知识达人网友:你可爱的野爹
- 2021-04-01 20:19
#include "iostream.h"
class complex
{
public:
complex()
{
real=imag=0.0;
}
complex(double r)
{
real=r;
imag=0.0;
}
complex(double r,double i)
{
real=r;
imag=i;
}
complex(complex&cp)
{
real=cp.real;
imag=cp.imag;
}
friend complex operator+(const complex&c1,const complex&c2);
friend complex operator-(const complex&c1,const complex&c2);
inline complex operator+=(const complex&c);
inline complex operator-=(const complex&c);
void print();
private:
double real,imag;
};
complex operator+(const complex&c1,const complex&c2)
{
return complex(c1.real+c2.real,c1.imag+c2.imag);
}
complex operator-(const complex&c1,const complex&c2)
{
return complex(c1.real-c2.real,c1.imag-c2.imag);
}
inline complex complex::operator+=(const complex&c)
{
return(real+c.real,imag+c.imag);
}
inline complex complex::operator-=(const complex&c)
{
return(real-c.real,imag-c.imag);
}
void complex::print()
{
if (imag<0)
{
cout< }
else
{
cout< }
}
int main()
{
complex c1(1, 2);// 定义一个值为1 + 2i的复数c1
complex c2(2);// 定义一个值为2的复数c2
complex c3(c1);// 用拷贝构造函数创建一个值同c1的新复数
c3.print();// 打印c3的值
c1=c1 + c2 + c3; // 将c1加上c2再加上c3赋值给c1
c2-=c3; // c2等于c3求负
c3 = c2 - c1;// c3等于c2减去c1
c3.print(); // 再打印运算后c3的值
return 0;
}
class complex
{
public:
complex()
{
real=imag=0.0;
}
complex(double r)
{
real=r;
imag=0.0;
}
complex(double r,double i)
{
real=r;
imag=i;
}
complex(complex&cp)
{
real=cp.real;
imag=cp.imag;
}
friend complex operator+(const complex&c1,const complex&c2);
friend complex operator-(const complex&c1,const complex&c2);
inline complex operator+=(const complex&c);
inline complex operator-=(const complex&c);
void print();
private:
double real,imag;
};
complex operator+(const complex&c1,const complex&c2)
{
return complex(c1.real+c2.real,c1.imag+c2.imag);
}
complex operator-(const complex&c1,const complex&c2)
{
return complex(c1.real-c2.real,c1.imag-c2.imag);
}
inline complex complex::operator+=(const complex&c)
{
return(real+c.real,imag+c.imag);
}
inline complex complex::operator-=(const complex&c)
{
return(real-c.real,imag-c.imag);
}
void complex::print()
{
if (imag<0)
{
cout<
else
{
cout<
}
int main()
{
complex c1(1, 2);// 定义一个值为1 + 2i的复数c1
complex c2(2);// 定义一个值为2的复数c2
complex c3(c1);// 用拷贝构造函数创建一个值同c1的新复数
c3.print();// 打印c3的值
c1=c1 + c2 + c3; // 将c1加上c2再加上c3赋值给c1
c2-=c3; // c2等于c3求负
c3 = c2 - c1;// c3等于c2减去c1
c3.print(); // 再打印运算后c3的值
return 0;
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯