C++输入输出运算符重载

成员函数输出重载

Human.h

#pragma once
#include<string>
#include <ostream>
class Human{
public:
	Human(const char* name, int age, int salare,int DarkHouse);
	~Human();
	std::ostream& operator<<(std::ostream& os);

private:
	char* name;
	int age;
	int salare;
	int DarkHouse;
	unsigned int id;
	static int last_iD;
};

std::ostream& Human::operator<<(std::ostream& os) {
	//cout<<为ostream一个对象
	os << "姓名:" << name << "\t年龄:" << age << "\t薪资:"
		<< salare << "\t黑马值:" << DarkHouse << "\t编号:" << id << '\n';
	return os;   //返回cout继续输出
} 

main.cpp

#include"Human.h"
#include<iostream>

int main() {
	Human boy("Rock", 38, 58000, 5);
	//std::cout << boy << ;  相当于cout.operator<<(boy1)
	boy << std::cout;   //相当于boy.operator<<(cout);

    //如果继续输出
    //boy1<<(boy<<cout)  先执行括号内的,返回cout,再执行boy1<<cout
	system("pause");
	return 0;
}

运行结果:

 这张方法使用起来很不方便

方法2:使用友元函数

man.h

#pragma once
#include<string>
#include <ostream>
class Human{
public:
	Human(const char* name, int age, int salare,int DarkHouse);
	~Human();
	friend std::ostream& operator<<(std::ostream& os,const Human&human);
	friend std::istream& operator>>(std::istream& is, Human& human);

private:
	char* name;
	int age;
	int salare;
	int DarkHouse;
	unsigned int id;
	static int last_iD;
};

main.cpp

#include"Human.h"
#include<iostream>
#include<ostream>
using namespace std;


std::ostream& operator<<(std::ostream& os, const Human& human)
{
	//cout<<为ostream一个对象
	os << "姓名:" << human.name << "\t年龄:" << human.age << "\t薪资:"
		<< human.salare << "\t黑马值:" << human.DarkHouse << "\t编号:" << human.id << '\n';
	return os;
}

std::istream& operator>>(std::istream& is, Human& human) {
	string name;
	is >> name>>human.age >> human.salare >> human.DarkHouse >> human.id;
	human.name = new char[(name.length() + 1)*sizeof(char)];
    //.c_str()可以改成C字符串
	strcpy_s(human.name, (name.length() + 1) * sizeof(char), name.c_str());
	return is;
}
int main() {
	Human boy1("Rock", 38, 58000, 5);
	Human boy2("Jack", 25, 50000, 10);
	cout << "输出运算符重载" << endl;
	std::cout << boy1 << boy2;     //相当于cout.operator(boy1)
	//boy << std::cout;   //相当于boy.operator(cout);
	cout << "\n输入运算符重载" << endl;
	cin >> boy1 >> boy2;
	cout << "\n输出运算符重载" << endl;
	std::cout << boy1 << boy2;
	system("pause");
	return 0;
}

运行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值