类和对象(中)——拷贝构造函数详解

目录

1.1 概念

1.2 特征


1.1 概念

拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用。

1.2 特征

拷贝构造函数也是特殊的成员函数,其特征如下:

        1.拷贝构造函数是构造函数的一个重载形式

以Data类为例:

class Date
{
public:
	Date(int year = 0, int month = 0, int day = 0)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Data& d)//拷贝构造函数
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
private:
	int _year;
	int _month;
	int _day;	
};

int main()
{
	Date d1(2022, 11, 20);
	Date d2(d1);//用已存在的对象d1来创建新对象d2
	return 0;
}

        2.拷贝构造函数的参数只有一个必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用。

         3.若未显式定义,编译器会生成默认的拷贝构造函数。默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。

编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的。

注意:

        语法上:如果用户没有显式定义,编译器会生成一份

        编译器实际实现:编译器不一定会生成,但是会完成拷贝的工作      

以Data类为例:

class Date
{
public:
	Date(int year = 0, int month = 0, int day = 0)
	{
		_year = year;
		_month = month;
		_day = day;
	}

private:
	int _year;
	int _month;
	int _day;	
};

int main()
{
	Date d1(2022, 11, 20);
	Date d2(d1);
	return 0;
}

 发现编译器并没有生成拷贝构造函数,但是完成了拷贝构造的工作。

        4.编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式定义吗?

下面用栈Stack类验证:

会发现下面的程序会崩溃掉。

typedef int DataType;
class Stack
{
public:
	Stack(size_t capacity = 3)
	{
		_array = (DataType*)malloc(sizeof(DataType)*capacity);
		if (NULL == _array)
		{
			perror("malloc申请空间失败!!!");
				return;
		}
		_capacity = capacity;
		_size = 0;
	}
	void Push(const DataType& data)
	{
		// CheckCapacity();
		_array[_size] = data;
		_size++;
	}
	void Pop()
	{
		if (Empty())
			return;

		_size--;
	}
	DataType Top()
	{
		assert(!Empty());
		return _array[_size - 1];
	}

	bool Empty()
	{
		return 0 == _size;
	}


	int Size()
	{
		return _size;
	}
	~Stack()
	{
		if (_array)
		{
			free(_array);
			_array = nullptr;
			_capacity = 0;
			_size = 0;
		}
	}


private:
	DataType* _array;
	int _capacity;
	int _size;

};
int main()
{
	Stack s1;
	s1.Push(1);
	s1.Push(2);
	Stack s2(s1);
    return 0;//在程序结束时,在s2释放资源后,s1调用析构函数时释放资源时,程序会崩溃掉
}

 注意:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝。

        5.拷贝构造函数典型调用场景:

              (1)使用已存在对象创建新对象

              (2)函数参数类型为类类型对象

              (3)函数返回值类型为类类型对象

class Date
{
public:

	Date(int year, int minute, int day)
	{
		cout << "Date(int,int,int):" << this << endl;
	}
	Date(const Date& d)
	{
		cout << "Date(const Date& d):" << this << endl;
	}

	~Date()
	{
		cout << "~Date():" << this << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
Date Test(Date d)
{
	Date temp(d);
	return temp;
}
int main()
{
	Date d1(2022, 11, 20);
	Test(d1);
	return 0;
}

为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值