【C++】拷贝构造函数典型题目解析

1 题目实例

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, 1, 13);
	Test(d1);
	return 0;
}

2 结果分析 

Date(int,int,int):00D3FE6C
Date(const Date& d):00D3FD5C
Date(const Date& d):00D3FD30
Date(const Date& d):00D3FD8C
~Date():00D3FD30
~Date():00D3FD5C
~Date():00D3FD8C
~Date():00D3FE6C

执行过程

  1. 创建对象 d1

    Date d1(2022, 1, 13);
    

    输出:

    Date(int,int,int):00D3FE6C
    
  2. 调用函数 Test

    Test(d1);
    
    • 传递参数 d1 时,调用拷贝构造函数:

      Date(const Date& d)
      

      输出:

      Date(const Date& d):00D3FD5C
      
    • Test 函数内部,创建临时对象 temp,再次调用拷贝构造函数:

      Date temp(d);
      

      输出:

      Date(const Date& d):00D3FD30
      
    • 返回 temp 时,调用拷贝构造函数:

      return temp;
      

      输出:

      Date(const Date& d):00D3FD8C
      
  3. 析构函数调用

    • tempTest 函数结束时被销毁:

      ~Date()
      

      输出:

      ~Date():00D3FD30
      
    • 传递给 Test 函数的临时对象d被销毁:

      ~Date()
      

      输出:

      ~Date():00D3FD5C
      
    • Test 函数返回创建的临时对象被销毁:

      ~Date()
      

      输出:

      ~Date():00D3FD8C
      
    • 最后,d1 被销毁:

      ~Date()
      

      输出:

      ~Date():00D3FE6C
      

总结

通过这个例子,我们可以看到拷贝构造函数在对象传递和返回时的调用情况,以及对象生命周期结束时析构函数的调用顺序。这有助于理解对象的内存管理和生命周期。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值