C++小白入门 全目录(必读)
运算符重载
运算符重载是函数重载的一种形式,只不过这种函数的名字不是用户自己定义的,而是一个运算符作为函数的名字。
运算符重载是为了让类的行为看起来更自然,代码可读性更高,程序的可扩展性更高。
比如,输出操作符重载。可以让一个复杂的类型也可以像整形这样的基础类型一样输出到控制台,输出到文件等任何流对象上。
Student stu("001", "张三", "男", "1990-02-12");
std::cout<<std<<std::endl;
输入输出操作符重载
下面我们以学生类Student为例,来展示如何让学生类对象像整形一样支持输入输出
#include <iostream>
#include <string>
//学生类型
class Student
{
//输入操作符重载:将外部获取到的数据存到Student对象上
friend std::istream& operator>>(std::istream& is, Student& stu);
//输出操作符重载:讲Student对象的数据输出到目的地(比如控制台屏幕、文件、字符串流)
friend std::ostream& operator<<(std::ostream& os, const Student& stu);
public:
std::string m_id;//学号
std::string m_name;//姓名
};
std::istre