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

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