C++ 拷贝构造函数的调用时机

C++ 拷贝构造函数在下面三种情况下调用:

(1)使用一个已经创建的对象来初始化一个对象

(2)用值传递的方式给函数参数传值

(3)值方式返回局部对象

 

(1)使用一个已经创建的对象来初始化一个对象

#include "iostream"
using namespace std;
class Person
{
public:
	Person()
	{
		cout << "默认构造函数" << endl;
	}
	Person(int age)
	{
		m_Age = age;
		cout << "有参构造函数" << endl;
	}
	Person(const Person & p)
	{
		cout << "拷贝构造函数" << endl;
		m_Age = p.m_Age;
	}
	~Person()
	{
		cout << "调用析构函数" << endl;
	}
	int m_Age;
};

void test1()
{
	Person p1(100);
	Person p2(p1);
	cout << "p2的年龄:"<<p2.m_Age<<endl;
}

int main()
{
	test1();
	return 0;
}

(2)用值传递的方式给函数参数传值

#include "iostream"
using namespace std;
class Person
{
public:
	Person()
	{
		cout << "默认构造函数" << endl;
	}
	Person(int age)
	{
		m_Age = age;
		cout << "有参构造函数" << endl;
	}
	Person(const Person & p)
	{
		cout << "拷贝构造函数" << endl;
		m_Age = p.m_Age;
	}
	~Person()
	{
		cout << "调用析构函数" << endl;
	}
	int m_Age;
};

void test(Person p)
{
}

void test1()
{
	Person p;
	test(p);
}
int main()
{
	test1();
	return 0;
}

(3)值方式返回局部对象

#include "iostream"
using namespace std;
class Person
{
public:
	Person()
	{
		cout << "默认构造函数" << endl;
	}
	Person(int age)
	{
		m_Age = age;
		cout << "有参构造函数" << endl;
	}
	Person(const Person & p)
	{
		cout << "拷贝构造函数" << endl;
		m_Age = p.m_Age;
	}
	~Person()
	{
		cout << "调用析构函数" << endl;
	}
	int m_Age;
};

Person test()
{
	Person p1;
	return p1;
}

void test1()
{
	Person p = test();
}
int main()
{
	test1();
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章