流插入和流提取的重载

我们知道流插入和流提取仅仅对内置类型起作用,那么当我们需要将流插入和流提取对自定义类型起作用时,只能对流插入和流提取重载了

class Date
{
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print() const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;
	//流插入的重载
	cout << d1;
	return 0;
}

我们无法将cout流插入对d1进行打印

那么我们将 << 进行重载

 

我们需要将  << 进行重载,需要知道cout对象的类型

cout对象的类型  是ostream

	void operator<<(ostream& out)  //进行重载
	{
		out << _year << "-" << _month << "-" << _day << endl;
	}

可这样子并不行

 原因还是因为隐藏指针this

运算符重载里面,如果是双操作数的操作符重载

第一个操作数传给this指针(左参数),第二个操作数传给(右参数)

 那么我们可以返过来---怎么反过来呢

这样子是可以解决问题,可是用法太奇怪了(太别扭了) ,不推荐

那么上面分析知道流提取不适合,重载成成员函数  --那么我们把他放在全局里(没有了this指针的影响)

 放在全局右面临类的私有成员变量无法在类外访问的问题,那么要将私有成员变量设成公有肯定是不合适的了

那么我们可以引入有元函数:将operator<< 重载函数放在类内,可以访问类内的私有成员变量

class Date
{
	//有元函数
	friend void operator<<(ostream& out, const Date& d)
	{
		out << d._year << "-" << d._month << "-" << d._day << endl;
	}
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print() const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;

	cout << d1;//这样子就可以了

	return 0;
}

可是当需要连续输出是却不支持

 那么原因是

 我们需要将cout进行返回

class Date
{
	//有元函数
	friend ostream& operator<<(ostream& out, const Date& d)
	{
		out << d._year << "-" << d._month << "-" << d._day << endl;
		return out;
	}
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print() const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;
	Date d2;

	cout << d1 << d2;  

	//cou<<d1  调用完返回out
	//out<<d2  这样子就可以连续输出了

	return 0;
}

 上面就是对流插入重载函数的讲解,对流提取也是同理的

class Date
{
	//有元函数
	friend istream& operator>>(istream& in, Date& d)
	{
		in >> d._year >> d._month >> d._day;
		return in;
	}
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print() const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1;
	Date d2;

	//d1.Print();
	//cin >> d1;
	//d1.Print();

	//d1.Print();
	//d2.Print();
	//cin >> d1>>d2;
	//d1.Print();
	//d2.Print();
	
	return 0;
}

以上便是对流插入和流提取重载的讲解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值