C++运算符(+,前置++,后置++,<<)重载,操作复数

#include<iostream>
using namespace std;
class Complex
{
//类外不能访问类的私有成员 所以使用友元函数
friend Complex& operator+(Complex &c1,Complex &c2); 
friend Complex& operator++(Complex& c1);
friend Complex& operator++(Complex& c1,int);
friend ostream& operator<<(ostream& out,Complex& c1);
public:
	Complex(int a=0,int b=0)
	{
		this->a=a;
		this->b=b;
	}
	void Print()
	{
	cout<<a<<"+"<<b<<"i"<<endl;	
		
	}
	//成员函数法重载运算符—实现复数相减 
	Complex& operator-(Complex &c2)
	{
		Complex temp(this->a-c2.a,this->b-c2.b);
		return temp;	
	}
	//成员函数法重载前置--
	Complex& operator--() 
	{
		this->a--;
		this->b--;
		return *this;
	}
	//成员函数法重载后置--
	Complex& operator--(int) 
	{
		Complex temp=*this;
		this->a--;
		this->b--;	
		return temp;
	}
private:
	int a;
	int b;
};

//全局函数法重载运算符+ 实现复数相加 
	Complex& operator+(Complex &c1,Complex &c2)
	{
		Complex temp(c1.a+c2.a,c1.b+c2.b);
		return temp;
	}
	//全局函数法重载前置++ 
	Complex& operator++(Complex& c1)
	{
		Complex temp(c1.a++,c1.b++)	;
		return temp;
	}
	//全局函数法重载后置++ 
	Complex& operator++(Complex& c1,int)
	{
		Complex temp=c1;
		c1.a++;
		c1.b++;
		return temp;
			
	}
	//全局函数重载<<
	ostream& operator<<(ostream& out,Complex& c1)
	{
		out<<c1.a<<"+"<<c1.b<<"i"<<endl;
	} 
int main()
{
	Complex c1(1,2);
//	Complex c2(1,2);
//	Complex c3=c1+c2;
//	Complex c4=c1-c2;
//	c3.Print();
//	c4.Print();
//	++c1;
//	++c1;
//	--c1;
//	c1++;
//	c1--;
//	c1--;
//	c1.Print();
	cout<<c1<<"链式";
	
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页