栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

成员函数输出重载

Human.h

#pragma once
#include
#include 
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

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

    //如果继续输出
    //boy1<<(boy< 

运行结果:

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

方法2:使用友元函数

man.h

#pragma once
#include
#include 
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
#include
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;
}

运行结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号