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

C++基础知识 - 赋值构造函数

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

C++基础知识 - 赋值构造函数

赋值构造函数

如果没有定义赋值构造函数,编译器会自动定义“合成的赋值构造函数”,
与其他合成的构造函数,是“浅拷贝”(又称为“位拷贝”)。

定义: 
Human& operator=(const Human& other);

实现: 
Human& Human::operator=(const Human& other){
	//当other = other时;
	if (this == &other) return *this;	

	//假如 f1 = f2;
	//自动调用, f1.operator=(f2)
	this->name = other.name;
	this->age = other.age;
	this->sex = other.sex;

	strcpy_s(this->addr,ADDR_LEN, other.addr);
	//返回对象的引用,是为了做链式处理: f1 = f2 = f3;
	return *this;
}

调用: 
对象赋值时自动调用
	//调用赋值构造函数
	lisi = zhangsan;

 
Human.h

#pragma once
#include 
#include 
#include 
using namespace std;

class Human {
public:		
	Human();
	~Human();
	Human(string name, int age, string sex);

	//定义了一个赋值构造函数
	Human& operator=(const Human& other);

	string getName() const;
	string getSex() const;
	int getAge() const;
	const char* getAddr()const;
	void setAddr(char* addr);
	void description() const;	
private:		
	string name;	//姓名
	string sex;		//性别
	int age;		//年龄
	char* addr;		//地址
};

 
Human.cpp

#include "Human.h"
#define		ADDR_LEN		64

Human::Human() {
	name = "无名";
	sex = "未知";
	age = 18;
	const char* addr_s = "China";
	addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, addr_s);
}

Human::Human(string name, int age, string sex) {
	this->age = age;
	this->name = name;
	this->sex = sex;
	const char* addr_s = "China";
	addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, addr_s);
}

Human& Human::operator=(const Human& other){
	//当other = other时;
	if (this == &other) return *this;	

	//假如 f1 = f2;
	//自动调用, f1.operator=(f2)
	this->name = other.name;
	this->age = other.age;
	this->sex = other.sex;

	strcpy_s(this->addr,ADDR_LEN, other.addr);
	//返回对象的引用,是为了做链式处理: f1 = f2 = f3;
	return *this;
}

string Human::getName() const {
	return name;
}

string Human::getSex() const {
	return sex;
}

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

const char* Human::getAddr() const{
	return addr;
}

void Human::setAddr(char* addr){
	if (!addr) 	return;
	strcpy_s(this->addr, ADDR_LEN, addr);
}

 
main.cpp

#include "Human.h"
using namespace std;

void showMsg(const Human &man1, const Human& man2) {
	cout << "张三地址: " << man1.getAddr() << endl;
	cout << "李四地址: " << man2.getAddr() << endl;
}

int main(void) {
	Human zhangsan("张三", 18, "男");	
	Human lisi;

	//调用赋值构造函数
	lisi = zhangsan;

	cout << "张三修改地址前" << endl;
	showMsg(zhangsan, lisi);
	
	zhangsan.setAddr((char*)"新加坡");
	cout << "张三修改地址后" << endl;
	showMsg(zhangsan, lisi);

	system("pause");
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738053.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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