关于拷贝构造函数调用情况的理解

关于拷贝构造函数调用情况的理解

C++中拷贝构造函数调用时机通常有三种情况

  • 使用该类的一个已经创建完毕的对象来初始化该类的一个新对象
  • 值传递的方式给函数参数传值(即函数的形参是类的对象)
  • 以值方式返回局部对象(即函数的返回值是类的对象)

具体的理解如下:用代码说明

  1. 情况一:
#include<iostream>
using namespace std;
class Person
{
public:
	Person()
	{
		cout << "调用无参构造函数" << endl;
	}
	Person(int age)
	{
		m_age = age;
		cout << "调用有参构造函数" << endl;
	}
	Person(const person& p)
	{
		m_age = p.m_age;
		cout << "调用拷贝构造函数" << endl;

	}
	~Person()
	{
		cout << "调用析构函数" << endl;
	}
	int m_age;
};
void test01()
{
	Person p1(10);
	person p2(p1);
}
int main()
{
	test01();
	return 0;
}

在这里插入图片描述
此情况为最常用情况,可以使用输入法可以使用代入法。

  1. 情况2:
#include<iostream>
using namespace std;
class Person
{
public:
	Person()
	{
		cout << "调用无参构造函数" << endl;
	}
	Person(int age)
	{
		m_age = age;
		cout << "调用有参构造函数" << endl;
	}
	Person(const person& p)
	{
		m_age = p.m_age;
		cout << "调用拷贝构造函数" << endl;

	}
	~Person()
	{
		cout << "调用析构函数" << endl;
	}
	int m_age;
};
void doWork(Person p1){}
void test02()
{
	Person p;
	doWork(p);
}
int main()
{
	test02();
	return 0;
}

在这里插入图片描述
图中:doWork(p)中的p是通过上边Person类创建的对象p,是实参,调用doWork 函数时,void doWork(Person p)中的p是通过拷贝构造函数复制的临时的,二者不是一个东西。

  1. 情况3:
#include<iostream>
using namespace std;
class Person
{
public:
	Person()
	{
		cout << "调用无参构造函数" << endl;
	}
	Person(int age)
	{
		m_age = age;
		cout << "调用有参构造函数" << endl;
	}
	Person(const person& p)
	{
		m_age = p.m_age;
		cout << "调用拷贝构造函数" << endl;

	}
	~Person()
	{
		cout << "调用析构函数" << endl;
	}
	int m_age;
};
void doWork2()
{
	Person p1;
	return p1;
}
void test03()
{
	Person p=doWork2();
}
int main()
{
	test03();
	return 0;
}

在这里插入图片描述
图中:通过默认构造返回p1,而且是一个局部对象,以值的形式返回局部对象,不会直接返回p1这个对象,会调用拷贝构造把p1拷贝一个新的对象返回给外边,所以p和p1不是一个东西,p是通过拷贝构造复制的p1。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值