C++ 自加运算符重载

顺便学习使用“<<”与“>>”的重载

#include<iostream>
using namespace std;

class C
{
	//重载“<<”与“>>”,作为全局函数,作为类的友元,访问类的私有成员变量
	friend ostream & operator <<(ostream&out, C&c);
	friend istream & operator >>(istream&in, C&c);
private:
	int b;
public:
	C(int b)
	{
		this->b = b;
	}
	C& operator ++()//代表前缀自加
	{
		this->b += 1;
		return *this;
	}
	const C operator++(int)//代表后缀自加,int纯粹只是为了区分前后缀
	{
		int oldb = this->b;
		++(*this);//使用前缀自加,统一自加行为
		return C(oldb);
	}
	C(const C & c)
	{
		this->b = c.b;
	}

	void print()
	{
		cout << b << endl;
	}
};

ostream &operator <<(ostream&out, C&c)
{
	out << c.b;
	return out;
}

istream &operator >>(istream&in, C&c)
{
	cout << "请输入b值:";
	in >> c.b;
	if (!in)
		c.b = 0;
	return in;
}

int main()
{
	C c1(2);
	cout << "c1:" << c1 << endl;
	cin >> c1;
	cout << "c1:" << c1 << endl;
	C c2(c1);
	cout << "c2:" << c2 << endl;
	C c3 = c1++;
	//C c4 = c1++++;//后面的++想修改c1++返回的const对象,所以报错
	cout << "c1:" << c1 << endl;
	cout << "c3:" << c3 << endl;
	C c5 = ++c1;
	cout << "c1:" << c1 << endl;
	cout << "c5:" << c5 << endl;
	C c6 = ++++c1;
	cout << "c1:" << c1 << endl;
	cout << "c6:" << c6 << endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值