C++基础知识 - 拷贝构造函数

拷贝构造函数

  • 拷贝构造函数,它只有一个参数,参数类型是本类的引用。
  • 复制构造函数的参数可以是 const 引用,也可以是非 const 引用。 一般使用前者,这样既能以常量对象(初始化后值不能改变的对象)作为参数,也能以非常量对象作为参数去初始化其他对象。一个类中写两个复制构造函数,一个的参数是 const 引用,另一个的参数是非 const 引用,也是可以的。
定义: 
Human(const Human &other);

实现: 
//拷贝构造函数
Human::Human(const Human& other){
   
	//把other对象的数据拷贝到另一个对象的私有数据
	this->name = other.name;
	this->sex = other.sex;
	this->age = other.age;
}


调用: 
对象初始化时,另一个对象赋值给对象本身,就会调用
	Human zhangsan(18, "张三", "男");
	
	//把 zhangsan 赋值给 lisi
	Human lisi = zhangsan;	//自动调用拷贝构造函数

1. 手动定义的拷贝构造函数

Human.h

#pragma once
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;

class Human {
   
public:		
	Human();
	Human(int age, string name, string sex);
	//手动定义了一个拷贝构造函数
	Human(const Human &other);

	string getName() const;
	string getSex() const;
	int getAge() const;
	void description() const;	//描述信息
private
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值