赋值构造函数

赋值构造函数:
一,编译器自动合成的构造函数
二,自定义的赋值构造函数

一,编译器自动合成的构造函数

#include <iostream>
#include <string>

using namespace std;

#define ADDR_LEN 64

//定义“人类”
class Human {
public: 
	Human(); //构造函数,可以写在类里面(由内联函数的效果),也可以写在外面

	// =运算符的重载
	//Human& operator=(const Human& other);

	void eat(); //类里面的方法,又称为成员函数
	void sleep();
	void work();
	void play();
	void description() const;
	void setAddr(const char* addr);

	string getName() const; //加const之后就不能在里面修改里面的值
	int getAge();
	int getSalary() const;

private:
	//类内初始值,C++11以上的版本才支持
	//在创建C++对象的时候,一开始就设定一个初始值,仅适用于特殊场合
	string name = "牛少侠";
	int age = 23;
	int salary = 10000;

	char* addr;
};

void Human::eat() {
	cout << "吃鸡屁股, 喝可乐!" << endl;
}

void Human::sleep() {
	cout << "夜深了!上床睡觉!" << endl;
}

void Human::work() {
	cout << "我在工作..." << endl;
}

void Human::play() {
	cout << "玩奇幻角色扮演!" << endl;
}

string Human::getName() const { //加const之后就不能在里面修改里面的值
	return name;
}

void Human::description() const{
	cout << "name: " << name
		<< "  age: "   << age
		<< "  salary: " << salary 
		<< "  地址:" << addr << endl;

	cout << (int)addr << endl;
}

void Human::setAddr(const char* addr) {
	if (!addr){
		return;
	}

	strcpy_s(this->addr, ADDR_LEN, addr);
	cout << (int)this->addr << endl;
}

int Human::getAge() {
	return age;
}

int Human::getSalary() const{
	return salary;
}

//没有设置类内初始值时,进行手动构造函数
Human::Human() {
	name = "无名";
	age = 18;
	salary = 30000;

	addr = new char[ADDR_LEN];
	strcpy_s(this->addr, ADDR_LEN, "China");
}

int main(void) {
	Human f1, f2;
	f2 = f1;	//调用赋值函数,位拷贝(浅拷贝)

	f1.description();
	f2.description();

	cout << "f1改国籍之后" << endl;

	f1.setAddr("法国");
	f1.description();
	f2.description();
	
	return 0;
}

输出为:
在这里插入图片描述
这时,是编译器自动生成的赋值构造函数,进行位拷贝(浅拷贝)

二,自定义的赋值构造函数
需要在类的public中进行声明:

class Human {
public: 
	// =运算符的重载
	Human& operator=(const Human& other);

赋值构造函数的具体实现

//赋值构造函数
Human& Human::operator=(const Human &other) {
	//this指向对象本身
	//防止对象自己赋值给自己,例如:f1 = f1
	if (this == &other) {
		return *this;
	}

	//f2 = f1
	name = other.name;
	age = other.age;
	salary = other.salary;

	//深拷贝
	strcpy_s(addr, ADDR_LEN, other.addr);

	//在进行链式处理的时候,需要用到返回。 例如:f3 = f2 = f1; 
	return *this;
}

输出为:
在这里插入图片描述

根据情况,如果有必要,需要先释放自己的资源,

//赋值构造函数
Human& Human::operator=(const Human &other) {
	//this指向对象本身
	//防止对象自己赋值给自己,例如:f1 = f1
	if (this == &other) {
		return *this;
	}

	//f2 = f1
	name = other.name;
	age = other.age;
	salary = other.salary;

	//如果有必要,需要先释放自己的资源
	delete addr;
	addr = new char[ADDR_LEN];
	//深拷贝
	strcpy_s(addr, ADDR_LEN, other.addr);

	//在进行链式处理的时候,需要用到返回。 例如:f3 = f2 = f1; 
	return *this;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值