【C++ 基础篇:24】:【重要模板】C++ 输入输出运算符重载【以 Date 日期类为例】

系列文章说明

本系列 C++ 相关文章 仅为笔者学习笔记记录,用自己的理解记录学习!C++ 学习系列将分为三个阶段:基础篇、STL 篇、高阶数据结构与算法篇,相关重点内容如下:

  1. 基础篇类与对象(涉及C++的三大特性等);
  2. STL 篇学习使用 C++ 提供的 STL 相关库
  3. 高阶数据结构与算法篇手动实现自己的 STL 库设计实现高阶数据结构,如 B树、B+树、红黑树等。

学习集:



前言

  • 运算符重载函数写法相对固定,在上一期内容中,笔者已给大家介绍并设计实现了关系运算符的重载(点击跳转),解决的自定义类型 / 对象的比较!
  • 本篇文章中,笔者将与大家分享的是 自定义类型 / 对象 的输入输出问题!即:重载 C++ 输入输出运算符

一、自定义类型输入输出的问题

如下图所示:提示:没有与这些操作匹配的 输入 / 输出 运算符! C++本身仅支持内置数据类型的基本输入输出,对于我们自定义实现的类型(如:时间类、学生信息类等),需要自定义重载!

  • >>:流输入运算符;【所处头文件:istream;在 std 命名空间中】
  • <<:流输出运算符;【所处头文件:ostream;在 std 命名空间中】

在这里插入图片描述
在这里插入图片描述


二、C++ 输入输出运算符重载写法(以日期类为例)

1.时间类的基本框架

代码如下(示例):

#include<iostream>
using std::cout;
using std::endl;
using std::cin;

class Date {
    
    
public:
	Date(int year = 1970,int month = 1, int day = 1) 
		:_year(year),_month(month),_day(day)
	{
    
    

	}
	void Print() {
    
    
		cout << _year << "-" << _month << "-" << _day << endl;
	}


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

2.输入输出重载说明!

流输入流输出 本身也是对象,分别对应:istream 类ostream 类(关于数据流问题,会在后续内容中再分享!)


3.输入输出重载写法示例

代码如下(示例):注意代码中的注释!

#include<iostream>
using std::cout;
using std::endl;
using std::cin;
using std::istream;			/* 注意此处! */
using std::ostream;			/* 注意此处! */

class Date {
    
    
public:
	Date(int year = 1970,int month = 1, int day = 1) 
		:_year(year),_month(month),_day(day)
	{
    
    

	}
	void Print() {
    
    
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	
	/* 流输入输出的重载:注意两个函数的第二个参数写法! */
	friend ostream& operator << (ostream& out, const Date& d);
	friend istream& operator >> (istream& in, Date& d);
private:
	int _year;
	int _month;
	int _day;
};



/* 流输入输出的重载 */
inline ostream& operator << (ostream& out, const Date& d) {
    
    
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}
inline istream& operator >> (istream& in, Date& d) {
    
    
	in >> d._year >> d._month >> d._day;
	return in;
}

运行结果示例图(如下)

在这里插入图片描述


相关文章

1. 【C++ 基础篇:21】:friend 友元四连问:什么是友元?友元类?友元函数?什么时候用友元?
2. 【C++ 基础篇:22】:类的 const 对象 与 const 成员函数/方法 以及 类中涉及 const 的常见问题!
3. 【C++ 基础篇:23】:【重要模板】关系运算符重载的设计与实现: [ > 、 < 、 >= 、 <= 、 != 、 == ] 重载【以 Date 时间类为例】


猜你喜欢

转载自blog.csdn.net/weixin_53202576/article/details/131175788
今日推荐