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

这篇博客探讨了C++中的赋值构造函数。如果没有显式定义,编译器会提供一个默认的赋值构造函数,进行浅拷贝操作。文章通过示例代码Human.h, Human.cpp和main.cpp来阐述这一概念。" 112410401,10295786,IDEA REST Client:超越Postman的接口调试利器,"['开发工具', '接口测试', 'RESTful API', 'HTTP客户端']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

赋值构造函数

  • 如果没有定义赋值构造函数,编译器会自动定义“合成的赋值构造函数”,
    与其他合成的构造函数,是“浅拷贝”(又称为“位拷贝”)。
定义: 
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 <string>
#include <iostream>
#include <Windows.h>
using namespace std;

class 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值