1. 程式人生 > >過載C++中的++運算子(包含對+的過載)

過載C++中的++運算子(包含對+的過載)

正確程式碼: 

#include<iostream>
using namespace std;
class Complex
{
	friend ostream &operator << (ostream &out,const Complex &c);
	private:
		int m_a;
		int m_b;
	public:
		Complex();
		Complex(int a,int b);
		void print();
		Complex operator + (Complex &c1);
		Complex operator ++(int);  //後置++
		Complex &operator ++(); 
	//	ostream &operator << (ostream &out,Complex &c);  不能改 
}; 
Complex::Complex()
{
	m_a=1;
	m_b=1;
}
Complex::Complex(int a,int b)
{
	m_a=a;
	m_b=b;
}
void Complex::print()
{
	cout<<m_a<<"+"<<m_b<<"i"<<endl;	
}
Complex Complex:: operator +(Complex &c1)    //通過成員函式的方式過載 + 
{
	this->m_a=c1.m_a+this->m_a;
	this->m_b=c1.m_b+this->m_b;
	return *this;
}
ostream& operator << (ostream &out,const Complex &c)
{
	out<<c.m_a<<"+"<<c.m_b<<"i"<<endl;
	return out;
} 
Complex  Complex:: operator ++(int)
{
	Complex tmp=*this;
	m_a++;
	m_b++;
	return tmp;
}
Complex &Complex::operator ++()
{
	this->m_a++;
	this->m_b++;
	return *this;
}
int main()
{
	Complex c1(1,2);
	Complex c2(2,3);
	Complex c3(3,4);
	Complex c4;
//	c1.operator +(c2);
//	c1.print();
	cout<<"**********"<<endl;
//	c4=c2+c3;
	c4.print();
	cout<<"************************"<<endl;
	cout<< c1++ <<endl;
	cout<< ++c1 <<endl;
	return 0;
}

在編譯執行過程中第68,69行一直有錯誤,原因是<<運算子不支援c1++的格式,第5行和第38行Complex前沒有加 const修飾。(上圖程式碼已改正)

另外需要注意的是,第50行的&應該加在第二個Complex前面而不是operator前面。

在第14,15行函式宣告中,14行後置++函式宣告中operator前沒有加&而第15行前置++函式宣告中加了,原因是前置++返回引用,而後置++返回物件本身。

14行後置++中括號內的int 為佔位位元組。必須要寫。

執行結果: