#include <iostream>
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator+(Complex &c,Complex &b);
friend Complex operator-(Complex &c,Complex &b);
friend Complex operator*(Complex &c,Complex &b);
friend Complex operator/(Complex &c,Complex &b);
void display();
private:
double real;
double imag;
};
//下面定义成员函数
Complex operator+(Complex &a,Complex &b)
{
Complex c,d;
c.real=b.real+a.real;
c.imag=b.imag+a.imag;
return c;
}
Complex operator-(Complex &a,Complex &b)
{
Complex c;
c.real=b.real-a.real;
c.imag=b.imag-a.imag;
return c;
}
Complex operator*(Complex &a,Complex &b)
{
Complex c;
c.real=b.real*a.real-b.imag*a.imag;
c.imag=b.imag*a.real+b.real*a.imag;
return c;
}
Complex operator/(Complex &a,Complex &b)
{
Complex c;
double d;
d=a.real*a.real+a.imag*a.imag;
c.real=(b.real*a.real+b.imag*a.imag)/d;
c.imag=(b.imag*a.real-b.real*a.imag)/d;
return c;
}
void Complex::display()
{
std::cout<<real<<","<<imag<<"i"<<std::endl;
}
//下面是测试函数
int main()
{
Complex c1(3,4),c2(5,-10),c3;
std::cout<<"c1=";
c1.display();
std::cout<<"c2=";
c2.display();
c3=c1+c2;
std::cout<<"c1+c2=";
c3.display();
c3=c1-c2;
std::cout<<"c1-c2=";
c3.display();
c3=c1*c2;
std::cout<<"c1*c2=";
c3.display();
c3=c1/c2;
std::cout<<"c1/c2=";
c3.display();
return 0;
}
运行结果:
8_2_2友元函数复数类
最新推荐文章于 2024-04-26 20:18:56 发布