【c++小白自学笔记】输出/输入运算符重载

C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。您可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。


输出运算符

cout是ostream的一个对象

#include  <iostream>

using namespace std;
class  cstu
{
	private:
	int nage;

	cstu()
	{
		nage = 12;
	}
	friend void operator <<(ostream& os, const cstu &st);//通常类内的变量都为private,用友元函数可以解决这个问题

};
void operator <<(ostream& os, const cstu &st)//输出运算符必须放在类外
{
	os << st.nage;
}

int main()
{
	cstu st;
	cout << st;
	return 0;
}

在进行连续的输出时,例如cout <<st<<st;,函数必须有返回值


输入运算符

cout是istream的一个对象

#include  <iostream>

using namespace std;
class  cstu
{
public:
	int nage;
	double dbHeight;
	cstu()
	{
		nage = 12;
		dbHeight = 1.7;

	}
	void show()
	{

		cout << nage << dbHeight << endl;
	}
	friend istream& operator >> (istream& ist,  cstu &st);
};
istream& operator >> (istream& ist, cstu &st)
{
	ist >> st.nage >> st.dbHeight;
	
}

int main()
{
	cstu st;
	cin >> st;
	st.show();
	return 0;
}

有一个可以判断用户是否输入有误的函数

istream& operator >> (istream& ist, cstu &st)
{
	ist >> st.nage >> st.dbHeight;
	if (ist.fail())
	{
		cout << "error" << endl;
	}
	return ist;
}

若输入的数值形式有误,则输出error

也可以直接将变量的值返回初始值

istream& operator >> (istream& ist, cstu &st)
{
	ist >> st.nage >> st.dbHeight;
	if (ist.fail())
	{
		nage = 12;
		dbHeight = 1.7;
	}
	return ist;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值