输出运算符重载<<

使用两种方式来实现输出运算符重载

方式一:使用类的成员函数, 输出运算符重载 不推荐使用该方式, 该方式没有实际意义
方式一:ostream& operator<<(ostream &os) const;
方式二:推荐使用友元函数, 在类的外部实现输出运算符重载
方式二:friend ostream &operator<<(ostream &os, const Boy &boy);

使用友元函数实现输出运算符重载的时候要注意参数的先后顺序!!

Boy.h

#pragma once
#include <iostream>
#include <string>

using namespace std;

class Boy{
public:
	Boy(const char *name = NULL, int age = 0, int salary = 0, int darkHorse = 0);
	~Boy();

	//方式一, 使用类的成员函数, 输出运算符重载
	//该方式不适合, 该方式没有实际意义
	//ostream& operator<<(ostream &os) const;
	

	//方式二, 推荐使用友元函数
	friend ostream &operator<<(ostream &os, const Boy &boy);

	int getPower() const;	//综和值

public:
	char *name;			//姓名
	int age;			//年龄
	int salary;			//薪资
	int darkHorse;		//潜力值
	unsigned int id;	//编号
	static int LAST_ID;	//全局编号
	int power;			//综合能力值
};

Boy.cpp

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

int Boy::LAST_ID = 1;	//每一个boy的ID都是唯一的

Boy::Boy(const char *name, int age, int salary, int darkHorse)
{
	if (!name) {	
		name = "未命名";
	}

	int nameLength = strlen(name) + 1;	//name的长度
	this->name = new char[nameLength];	//+1表示字符串结束符
	strcpy_s(this->name, nameLength, name);

	this->age = age;
	this->salary = salary;
	this->darkHorse = darkHorse;
	this->power = 0;
	this->id = LAST_ID++;
}

Boy::~Boy()
{
	if (this->name) {	
		delete this->name;
	}
}

int Boy::getPower() const
{
	//比较规则: 薪资 * 潜力值 + (100 - 年龄) * 100
	int ret = this->salary * this->darkHorse + (100 - this->age) * 100;
	return ret;
}

//ostream &Boy::operator<<(ostream &os) const
//{
//	os	<< "ID: " << id
//		<< "\t姓名:" << name
//		<< "\t年龄:" << age
//		<< "\t薪资:" << salary
//		<< "\t潜力值:" << darkHorse;
//	return os;
//}

main.cpp

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

//使用友元函数实现输出运算符重载
ostream &operator<<(ostream &os, const Boy &boy) {
	os << "ID: " << boy.id
		<< "\t姓名:" << boy.name
		<< "\t年龄:" << boy.age
		<< "\t薪资:" << boy.salary
		<< "\t潜力值:" << boy.darkHorse;
	return os;
}

int main(void) {
	Boy boy1("白展堂", 30, 2000, 10);

	//调用 boy1.operator<<(cout)
	//不推荐使用类的成员函数
	//boy1 << cout;	

	//推荐使用友元函数
	cout << boy1 << endl;

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值