C++基础知识 - 重载<<和>>运算符

本文介绍了C++中重载输入输出运算符<<和>>的方法,包括不推荐的使用成员函数的方式以及推荐的使用友元函数的方式,以实现复杂对象的便捷输入输出。
摘要由CSDN通过智能技术生成

重载<<和>>运算符

  • 为什么要重载<< 和 >>
    为了更方便的实现复杂对象的输入和输出。
  • 在 C++ 中,左移运算符<<可以和 cout 一起用于输出,因此也常被称为“流插入运算符”或者“输出运算符”。
  • 实际上,<<本来没有这样的功能,之所以能和 cout 一起使用,是因为被重载了。
  • 两种方式实现:
    第一种使用成员函数,不推荐,该方式没有实际意义
    第二种使用友元函数实现

重载<<运算符 方式一:(使用成员函数, 不推荐,该方式没有实际意义)

Boy.h

#pragma once
#include <string>
#include <iostream> 	//包含头文件
using namespace std;

class Boy{
   
public:
	Boy(const string name = "无名", int age = 0, int salary = 0);

	//输出运算符重载
	ostream& operator<<(ostream& os) const;
private: 
	string name;//姓名
	int age;	//年龄
	int salary;	//薪资
};

Boy.cpp

#include <sstream>
#include "Boy.h"

Boy::Boy(const string name, int age, int salary){
   
    this->name = name;
    this->age = age;
    this->salary = salary;
}

//返回值是ostream的引用
ostream& Boy::operator<<(ostream& os) const{
   
    os << "姓名:" << name << "\t年龄:" << age << "\t薪资:" << salary;
    return os;
}

main.cpp

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值