c++专属成员函数之拷贝构造函数

拷贝构造函数特点:
1. 拷贝构造函数 是构造函数的一个重载形式 。(也就是说它本身也是构造函数)
2. 拷贝构造函数的 参数只有一个 必须是类类型对象的引用 ,使用 传值方式编译器直接报错 ,因为会引发无穷递归调用。
#include<iostream>
using namesapce std;
class Date
{
public:
 Date(int year = 1900, int month = 1, int day = 1)
 {
 _year = year;
 _month = month;
 _day = day;
 }
 // Date(const Date d) // 错误写法:编译报错,会引发无穷递归
 Date(const Date& d) //正确写法
 {
 _year = d._year;
 _month = d._month;
 _day = d._day;
 }
private:
 int _year;
 int _month;
 int _day;
};

void fun(Date d){
  //...
}
int main()
{
 Date d1;
 fun(d1);
 Date d2(d1);//通过调试去看过程
 return 0;
}

下面开始逐层说明上方的代码

我们开始调试,发现要执行fun()函数,要先传参d1,但是这里d1不是直接传参,而是调用类中的拷贝构造函数Date(const Date& d),然后把拷贝出来的d传参进fun()函数。

我们执行Date d2(d1)时,如果拷贝构造函数是Date(const Date d)没有引用&,那么我们会无穷重复刚才的过程,不断调用拷贝构造函数,编译器不允许这样做,会直接报错,因此一定要有引用。至于这里的const是防止你的函数写的有问题,不小心把原对象都给改变了。

当然,拷贝构造函数也可以改成下面这样,是一样的

//...
Date(const Date& d) //正确写法
 {
 this->_year = d._year;
 this->_month = d._month;
 this->_day = d._day;
 }
//...
Date d2(d1);
这里this就是d2的指针
3. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成
拷贝,这种拷贝叫做浅拷贝,或者值拷贝
#include<iostream>
using namesapce std;
class Date
{
public:
 Date(int year = 1900, int month = 1, int day = 1)
 {
 _year = year;
 _month = month;
 _day = day;
 }
private:
 int _year;
 int _month;
 int _day;
};

void fun(Date d){
  //...
}
int main()
{
 Date d1;
 Date d2(d1);//通过调试去看过程
 return 0;
}

我们会发现d2中的_year,_month,_day和d1都是一样的。那么我们是不是可以不写拷贝构造函数了呢?答案是不行的,我们来看下面这个例子

class Stack
{
public:
Stack()
{
	cout << "Stack()" << endl;

	_a = (int*)malloc(sizeof(int) * 4);
	if (nullptr == _a)
	{
		perror("malloc申请空间失败");
		return;
	}

	_capacity = 4;
	_top = 0;
}

	Stack(int capacity = 4)
	{
		cout << "Stack()" << endl;

		_a = (int*)malloc(sizeof(int) * capacity);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败");
			return;
		}

		_capacity = capacity;
		_top = 0;
	}

private:
	int* _a = nullptr;
	int _top = 0;
	int _capacity;
};
int main(){
  Stack st1;
  Stack st2(st1);
  return 0;//报错
}

这边st2调用拷贝构造函数会连开辟空间的地址都一模一样,也就是_a的值一样,到时候结束的时候调用析构函数,会连续两次清理同样的空间,那么就会报错,这也叫浅拷贝。这里就需要深拷贝,其实也就是复制的时候搞一块独立的新空间(深拷贝会在之后的博客中具体讲解,这里就先略过),那么清理空间就不会报错,这里就看一下深拷贝的函数即可

Stack(const Stack& st)
	{
		_a = (int*)malloc(sizeof(int) * st._capacity);
		if (nullptr == _a)
		{
			perror("malloc申请空间失败");
			return;
		}

		memcpy(_a, st._a, sizeof(int) * st._top);
		_top = st._top;
		_capacity = st._capacity;
	}

说点题外话,大型变量最好要引用返回,但是需要添加static延长生命周期

Stack& func(){
 static Stack st;//静态变量,出了作用域不会销毁,可以引用返回
 return st;
}
Stack func(){//出了作用域局部变量会销毁,空间也会销毁
//如果引用返回,返回的就是野指针。因此不能引用返回,需要在返回的时候复制一份同样的Stack变量返回
   Stack st;
   return st;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值