重载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 为占位字节。必须要写。

运行结果:

猜你喜欢

转载自blog.csdn.net/mmmmmmyy/article/details/81220886