C++中cout,cin实现自定义运算符重载


一、cout(流插入)

1.为什么内置类型可以直接实现呢??

编译器提供了对应的相关函数

在这里插入图片描述

对于自定义类型呢??

这就需要我们自己实现了


class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	ostream& operator<<(ostream& out)
	{
		out << _year << "年" << _month << "月" << _day << "日";
	}
private:
	int _year;
	int _month;
	int _day;
};

但是这样写的话,在main函数正常写会报错
在这里插入图片描述
c++规定: 双操作数的运算符,第一个参数是左操作数,第二个操作数是右操作数
❤️那我们放在类外边呢?❤️


class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
//private:
	int _year;
	int _month;
	int _day;
};

ostream&  operator<<(ostream& out,const Date&d1)
{
	out << d1._year << "年" <<d1. _month << "月" << d1._day << "日";
	return out;
}
int main()
{
	Date d1(2023, 11, 4);
   cout << d1;
	return 0;
}

在这样就可以编译通过,但是Date类中的成员变量就必须是共有。

💜这时我们可以通过友元函数进行实现💜

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	friend ostream& operator<<(ostream& out, const Date& d1);
private:
	int _year;
	int _month;
	int _day;
};

ostream&  operator<<(ostream& out,const Date&d1)
{
	out << d1._year << "年" <<d1. _month << "月" << d1._day << "日";
	return out;
}
int main()
{
	Date d1(2023, 11, 4);
   cout << d1;
	return 0;
}

二、cin(流提取)

流提取和流插入是差不多的,我们直接就看一下实现过程

class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	friend istream& operator>>(istream& in, const Date& d1);
private:
	int _year;
	int _month;
	int _day;
};

istream& operator>>(istream& in, const Date& d1)
{
	in>> d1._year >>  d1._month >> d1._day ;
	return in;
}
int main()
{
	Date d1;
	cout >> d1;
	return 0;
}

三.结论

⭐️ 其他的运算符一般都是实现为成员函数
⭐️ 流运算符必须实现到全局,这样才能让流对象做第一个参数,符合可读性
⭐️ 流本质为了解决自定义类型的输入输出问题,采用面向对象+运算符重载进行解决

总结

以上就是我们对C++中cout,cin实现自定义运算符重载的相关内容的详细介绍,希望对大家的学习有所帮助,仅供参考 如有错误请大佬指点我会尽快去改正 欢迎大家来评论~~~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lim 鹏哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值