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

运行结果:

 

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值