运算符重载,友元函数(C++)

设有描述复数的类 CComplex 定义如下:
class CComplex
{
double m_real;
double m_image;
public:
void setValue(double real,double image)
{
m_real=real;
m_image=image;
}
};
请使用友元函数实现如下重载:
 重载<<运算符,使得可以用 cout<<输出复数,每个复数输出的格式为:“实部+虚部*i”;
 重载+运算符,使得可以实现两个复数相加;
 重载+运算符,使得可以实现复数和实数的相加;
 重载前置++运算符,使得可以实现复数的实部和虚部分别加 1;
 重载后置++运算符,使得可以实现复数的实部和虚部分别加 1;
 在 main 函数中测试并试用这些运算符。
 

/*======================================================================
*学号:
*作业:E13
*功能:设有描述复数的类 CComplex 定义
请使用友元函数实现如下重载:
 重载<<运算符,使得可以用 cout<<输出复数,每个复数输出的格式为:
“实部+虚部*i”;
 重载+运算符,使得可以实现两个复数相加;
 重载+运算符,使得可以实现复数和实数的相加;
 重载前置++运算符,使得可以实现复数的实部和虚部分别加 1;
 重载后置++运算符,使得可以实现复数的实部和虚部分别加 1;
 在 main 函数中测试并试用这些运算符。
*作者:
*日期:2016.5.4
*=====================================================================*/

#include<iostream>

using namespace std;

class CComplex
{
	double m_real;
	double m_image;
public:
	void setValue(double real,double image)
	{
		m_real=real;
		m_image=image;
	}
	CComplex& operator+(CComplex &rhs);                        //实现两个复数相加
	CComplex& operator+(double x);                                //实现复数和实数相加
	CComplex &operator++();                                    //前自增
	CComplex operator++(int);                                  //后自增
	friend ostream &operator<<(ostream &o,const CComplex &t);

};

CComplex& CComplex::operator+(CComplex &rhs)
{
	m_real+=rhs.m_real;
	m_image+=rhs.m_image;
	return *this;
}

CComplex& CComplex::operator+(double x)
{
	m_real+=x;
	return *this;
}

CComplex& CComplex::operator++()                             //前自增
{
	++m_real;
	++m_image;
	return *this;
}

CComplex CComplex::operator++(int)                             //后自增
{
	CComplex ret=*this;
	++m_real;
	++m_image;
	return ret;
}

ostream &operator<<(ostream &o,const CComplex &t)
{
	o<<"复数为:"<<t.m_real<<"+"<<t.m_image<<"i"<<endl;
	return o;
}

//测试主函数
int main()
{
	CComplex a,b;
	double r1,i1,r2,i2;
	cout<<"请分别输入两个复数的实部和虚部:"<<endl;
	cin>>r1>>i1>>r2>>i2;

	cout<<"第一个复数为:";
	a.setValue(r1,i1);
	cout<<a;
	cout<<"第二个复数为:";
	b.setValue(r2,i2);
	cout<<b;

	cout<<"两个复数相加得:";
	cout<<a+b;

	cout<<"请输入一个实数:"<<endl;
	double x;
	cin>>x;
	cout<<"复数与实数相加得:";
	cout<<a+x;

	cout<<"复数前自增:";
	cout<<++a;

	cout<<"复数后自增:";
	cout<<a++;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ukco_well/article/details/86576571
今日推荐