C++中拷貝構造函數的四種調用方式

代碼

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
static int i = 0;
class Student
{
private:
	int age;
	string name;
public:
	/*
	構造函數
	*/
	Student(int age, string name)
	{
		this->age = age;
		this->name = name;

		cout << "構造函數" << endl;
	}
	/*
	無參構造函數
	*/
	Student() { cout << "無參構造函數" << endl; }
	/*
	拷貝構造函數
	*/
	Student(const Student & stur)
	{
		age = stur.age;
		name = stur.name;
		cout << "拷貝構造函數" << endl;
	}
	/*
	析構函數
	*/
	~Student()
	{
		cout << "析構函數" << endl;

	}
	void print()
	{
		cout << age << endl;
	}
};

Student fun(int age, string name)
{
	Student stu(age, name);   // stu是局部變量,在函數執行完將會進行析構
	return stu;//會存在Student temp = stu,在主調函數中如果有變量接受  temp的話就不會立刻釋放
}

void fun2(const Student stur)
{
	cout << "fun2" << endl;
}


return 0;
}

四種調用方法

int main()
{
	Student stu1(12,"lisi");

#if 0
	//第一種調用方式
	Student stu2(stu1);

	//第二種
	Student stu3 = stu1;

	//注:以下方式不行
	 Student stu3;
	 stu3 = stu1;// 這是先調用無參構造創建,然後再賦值
#endif
	//第三種作爲函數的返回值時會存在  Student temp = stu;
	fun(10, "張三");
	cout << "fun執行完了" << endl;//temp在此之前被析構,相當於匿名對象,使用完就會被析構

#if 0
	Student stu4 = fun(11, "王五");//這種情況  stu4= 這一過程沒有調用拷貝構造函數,而是直接將temp轉正爲stu4
	cout << "fun執行完了" << endl;//temp被轉正爲stu4

	//第四種,作爲函數參數使用時
	fun2(stu1);//存在Student stur = stu1

#endif
	

運行結果

方式1與2

方式3  不用變量接收,執行完以後臨時對象立刻被析構

 

方式3  使用變量接受,臨時對象轉正

方式4  存在Student stur = stu1

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