C++求源代码:定义复数类的一个友元函数 complex add(complex x,complex y),用于完成两个复数的加法
2个回答
推荐于2018-04-20
展开全部
以前自己写的简单复数运算类。
gcc, Microsoft Visual Studio 2010, 2013编译通过
complex.h(声明)
#include<iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex(double r=0,double i=0);
friend Complex operator + (Complex &,Complex &);
friend Complex operator + (double,Complex &);
friend Complex operator + (Complex &,double);
friend Complex operator - (Complex &,Complex &);
friend Complex operator - (double,Complex &);
friend Complex operator - (Complex &,double);
friend ostream &operator <<(ostream &,Complex &);
};
complex.cpp(定义)
#include"complex.h"
Complex::Complex(double r,double i)
{
real=r;
imag=i;
}
Complex operator + (Complex &c1,Complex &c2)
{
Complex ct;
ct.real=c1.real+c2.real;
ct.imag=c1.imag+c2.imag;
return ct;
}
Complex operator + (double r,Complex &c)
{
Complex ct;
ct.real=r+c.real;
ct.imag=c.imag;
return ct;
}
Complex operator + (Complex &c,double r)
{
Complex ct;
ct.real=r+c.real;
ct.imag=c.imag;
return ct;
}
Complex operator - (Complex &c1,Complex &c2)
{
Complex ct;
ct.real=c1.real-c2.real;
ct.imag=c1.imag-c2.imag;
return ct;
}
Complex operator - (double r,Complex &c)
{
Complex ct;
ct.real=r-c.real;
ct.imag=-c.imag;
return ct;
}
Complex operator - (Complex &c,double r)
{
Complex ct;
ct.real=c.real-r;
ct.imag=c.imag;
return ct;
}
ostream &operator <<(ostream &os,Complex &c)
{
if(c.real==0)
{
if(c.imag==0)
{
os<<0;
}
else
{
os<<c.imag<<'i';
}
}
else
{
if(c.imag==0)
{
os<<c.real;
}
else if(c.imag>0)
{
os<<c.real<<'+'<<c.imag<<'i';
}
else
{
os<<c.real<<c.imag<<'i';
}
}
return os;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询