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;
}

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