拷贝构造函数

1.什么是拷贝构造函数呢?

答:它是一种特殊的构造函数,用来完成同一类的对象初始化对象或者构建对象。

注意:他和普通构造函数一样,如果你自己不写系统就会调用默认拷贝函数,只不过它只能完成最基本的对象初始化对象的功能罢了。

class stu
{
	public:
	stu(const stu &m)//定义了一个拷贝构造函数
	{
		;//
	}
private:
	int a;
};
如上stu(const stu  &m)就是拷贝函数的书写形式,函数名字和类名相同,函数参数是一个常引用,只不过这个拷贝函数什么功能也没有完成。

接下来讲一讲拷贝函数的调用

1.

class stu
{
private:
	int a;
	int b;
public:
	stu(int x, int y)//类的内部定义构造函数
	 {
		a = x;
		b = y;
	 }
	stu(const stu &m)//定义了一个拷贝构造函数
	{
		;//
	}
	void display()//打印成员值
	{
		cout << a << " " << b << endl;
	}
};

int main()
{
	stu t1(1, 2);//将成员对象初始化为1,2
	stu t2 = t1;//当函数走到这一步会自动调用拷贝构造函,下面用图示证明
	            //用对象t1的成员值分别来初始化对象t2的成员值,
	            //因为这个拷贝构造函数没有功能语句,所以t2的值是乱码,下图证明
	t1.display();
	t2.display();
	getchar();
	return 0;
}

将上面的拷贝函数改成这个样子就可以实现正常的功能了

	stu(const stu &m)//定义了一个拷贝构造函数
	{
		a = m.a;
		b = m.b;//实现了赋值功能
	}

注:调用的时候使用stu t2(t1);这个语句和stu t2=t1;是等价的

2.

class stu
{
private:
	int a;
	int b;
public:
		stu(int x, int y)//类的内部定义构造函数
		{
			a = x;
			b = y;
		}
	stu(const stu &m)//定义了一个拷贝构造函数
	{
		a = m.a;
		b = m.b;
	}
	void display()//打印成员值
	{
		cout << a << " " << b << endl;
	}
};
void fun(stu p)//局部变量
{
	p.display();
}
int main()
{
	stu t1(5, 6);//将成员对象初始化为1,2
	fun(t1);//在这里先调用拷贝函数,然后在调用fun函数,用t1去初始话形参对象p
	getchar();
	return 0;
}

3.返回值为匿名对象的拷贝函数的调用(重)

①单纯的返回匿名对象

class stu
{
private:
	int a;
	int b;
public:
		stu(int x, int y)//类的内部定义构造函数
		{
			a = x;
			b = y;
		}
	stu(const stu &m)//定义了一个拷贝构造函数
	{
		a = m.a;
		b = m.b;
	}
	void display()//打印成员值
	{
		cout << a << " " << b << endl;
	}
	~stu()//析构函数
	{
		cout << "执行析构函数" << endl;
	}
};
stu fun()//返回值为匿名对象
{
	stu p(1,2);//执行普通构造函数初始化局部对象p
	return p;//在这里执行拷贝构造函数,创建一个匿名对象返回去
}
int main()
{
	fun();//调用函数,不过没有变量去接返回值
	getchar();
	return 0;
}

因为创建了两个对象一个p,一个匿名对象,所以 执行两次析构函数

②匿名对象 初始化 同类对象



③匿名对象赋值给给同类对象注意和初始化区分

class stu
{
private:
	int a;
	int b;
public:
	void display()//打印成员值
	{
		cout << a << " " << b << endl;
	}
	~stu()//析构函数
	{
		cout << "执行析构函数" << endl;
	}
		stu(int x, int y)//类的内部定义构造函数
		{
			a = x;
			b = y;
		}
	stu(const stu &m)//定义了一个拷贝构造函数
	{
		a = m.a;
		b = m.b;
	}
};
stu fun()//返回值为匿名对象
{
	stu p(5,6);//执行普通构造函数初始化局部对象p
	return p;//在这里执行拷贝构造函数,创建一个匿名对象返回去
}
int main()
{
	stu t1(1, 2);
	t1=fun();//调用函数,赋值给tl,然后被析构,因为他并没有转正成功
	t1.display();
	getchar();
	return 0;
}


  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值