C++对赋值运算符的重载

main.cpp

注意:

注意赋值运算符重载的返回类型 和参数类型。

返回引用类型,便于连续赋值

参数使用引用类型, 可以省去一次拷贝

参数使用const, 便于保护实参不被破坏。

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

int main()
{
	Boy boy1("zhs", 24, 20000, 10);
	Boy boy2, boy3;
	cout << boy1.description() << endl;
	cout << boy2.description() << endl;
	cout << boy3.description() << endl;

	cout << "----------------------------------" << endl;

	boy3 = boy2 = boy1;
	cout << boy1.description() << endl;
	cout << boy2.description() << endl;
	cout << boy3.description() << endl;



	system("pause");
	return 0;
}

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();
	Boy&operator=(const Boy&boy);
	string description();

private:
	char*name;
	int age;
	int salary;
	int darkHorse;  //黑马,潜力值
	unsigned int id;  //编号
	static int LAST_ID;
};

Boy.cpp

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

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

	this->name = new char[strlen(name) + 1];
	strcpy_s(this->name, strlen(name) + 1,name);

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

Boy::~Boy()
{
	if (name)
	{
		delete name;
	}
}

Boy & Boy::operator=(const Boy & boy)
{
	if (name)
	{
		delete  name; //释放原来的内存
	}
	name = new char[strlen(boy.name) + 1];//分配新的内存
	strcpy_s(name, strlen(boy.name) + 1, boy.name);

	this->age = boy.age;
	this->salary = boy.salary;
	this->darkHorse = boy.darkHorse;
	return*this;

}

string Boy::description()
{
	stringstream ret;
	ret << "ID:" << id << "\t姓名:" << name << "\t年龄:" << age << "\t薪资:"
		<< salary << "\t黑马系数:" << darkHorse;
	return ret.str();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值