C++学习之运算符重载综合练习

实现:
1、+号运算符重载
2、自定义输出数据类型,并实现递增,递减

#include<iostream>
#include<string>
using namespace std;

class mytype
{
friend	ostream& operator<<(ostream& cout, mytype a);//友元让其可以访问mytype的私有成员
friend  mytype operator+(mytype& a, mytype& b);

public:
	mytype()//默认构造函数(无参构造函数)
	{
		m_num = 0;
	}

	mytype(int A)//有参构造函数
	{
		this->m_num = A;
	}

	/*重载递增运算符*/
	mytype& operator++()//前置递增
	{
		m_num++;
		return *this;	
	}

	mytype operator++(int)//后置递增,加一个int占位符即可,返回的是一个值,不要返回一个局部变量的引用,用完就释放了
	{
		mytype temp = *this;//先记录一下当前的值,返回的也是这个值
		this->m_num++;
		return temp;
	}


	/*重载递减运算符*/
	mytype& operator--()//前置递减,
	{
		m_num--;
		return *this;
	}

	mytype operator--(int)//后置递减,返回的是一个值,不要返回一个局部变量的引用,用完就释放了
	{
		mytype temp = *this;
		m_num--;
		return temp;
	}

private:
	int m_num;

};

//重载<<输出运算符
ostream& operator<<(ostream& cout, mytype a)//本质:operator<<(cout,a);   最终简化成:cout<<a;
{
	cout << a.m_num << endl;
	return cout;
}

//重载+号运算符
mytype operator+(mytype& a,mytype& b)//本质:operator+(a, b);
{
	mytype temp;
	temp.m_num = a.m_num + b.m_num;
	return temp;
}

void main()
{
	//自定义输出数据类型,并实现递增,递减
	mytype M;
	cout << M;

	++M;  //本质:M.operator++();
	cout << M;
	--M;
	cout << M;
	cout << M++;
	cout << M;
	cout << M--;
	cout << M;
    
    //+号运算符重载
	mytype M1;
	mytype M2(10);
	mytype M3(10);

	M1 = M2 + M3;
	cout << M1;	
	cout<<operator+(M1, M3);//简化成:cout<<M1+M3;
}





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值