成员函数输出重载
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;
}
运行结果:
?
|