C++ 运算符重载-友元函数(复数类)

  • Post author:
  • Post category:其他

【问题描述】

请定义一个复数类,将+/-运算符重载为友元函数,实现复数与复数的加减及复数与浮点数的加减。

请根据给定的main函数,设计Complex类。

【样例输出】

a+b=(4)+(3i)

a-b=(2)+(5i)

a+100=(103)+(4i)

a-2.5=(0.5)+(4i)

100+a=(103)+(4i)

2.5-a=(-0.5)+(-4i)

#include  <iostream>
using  namespace  std;
class Complex{
	private:
		double  real;
		double  image;
	public :
		
		Complex(double  r=0,double  i=0):real(r),image(i){};
		void print()
		{
		cout<<"("<<real<<")+("<<image<<"i)";
	}
	friend Complex operator+(Complex c1,Complex c2);
	friend Complex operator-(Complex c1,Complex c2);
	friend Complex operator+(Complex c,double a);
	friend Complex operator+(double a,Complex c);
	friend Complex operator-(Complex c,double a);
	friend Complex operator-(double a,Complex c);
};
Complex operator+(Complex c1,Complex c2)
{
	return Complex(c1.real+c2.real,c1.image+c2.image);
}
Complex operator-(Complex c1,Complex c2)
{
	return Complex(c1.real-c2.real,c1.image-c2.image);
}
Complex operator+(Complex c,double a)
{
	return Complex(c.real+a,c.image);
}
Complex operator+(double a,Complex c)
{
	return Complex(a+c.real,c.image);
}
Complex operator-(double  a,Complex c)
{
	return Complex(a-c.real,0-c.image);
}
Complex operator-(Complex c,double  a)
{
	return Complex(c.real-a,c.image);
}

int  main()
{
        Complex  a(3,4),b(1,-1),c;
        c=a+b;
        cout<<"a+b=";
        c.print();
        cout<<endl;
        c=a-b;
        cout<<"a-b=";
        c.print();
        cout<<endl;
        c=a+100;
        cout<<"a+100=";
        c.print();
        cout<<endl;
        c=a-2.5;
        cout<<"a-2.5=";
        c.print();
        cout<<endl;
        c=100+a;
        cout<<"100+a=";
        c.print();
        cout<<endl;
        c=2.5-a;
        cout<<"2.5-a=";
        c.print();
        cout<<endl;
        return  0;
} 

版权声明:本文为YANG12345_6原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。