C++拷贝构造函数

#include <iostream>
using namespace std;


/*
二个特殊的构造函数
1)默认无参构造函数
	当类中没有定义构造函数时,编译器默认提供一个无参构造函数,并且
其函数体为空
2)默认拷贝构造函数
	当类中没有定义拷贝构造函数时,编译器默认提供一个默认拷贝构造函
数,简单的进行成员变量的值复制
*/


class Test
{
public:
	Test()
	{
		cout << "无参构造" << endl;
	}

	Test(int a) :m_a(a)
	{
		cout << "有参构造" << endl;
	}

	Test(const Test &another)
	{
		m_a = another.m_a;

		cout << "拷贝构造" << endl;
	}

	void test_print(void)
	{
		cout << "m_a:" << m_a << endl;
	}
	~Test()
	{
		cout << "析构函数" << endl;
	}
private:
	int m_a;

};

//拷贝构造的第一种场景:用对象1初始化对象2
void test1(void)
{
	cout << "test1:xxxxxxxxxxxxxxxxxxxxxxxxxx" << endl;
	Test t1(10);

	Test t2 = t1; //用 t1 初始化t2

	t2.test_print();

	cout << "test1: end xxxxxxxxxxxxxxxxxxxxx" << endl;

}

//拷贝构造的第二种场景:
void test2(void)
{
	cout << endl;
	cout << endl;
	cout << "test2:xxxxxxxxxxxxxxxxx" << endl;
	Test t1(20);
	Test t2(t1);
	t2.test_print();
	cout << "test2: end xxxxxxxxxxxxxxxxxx" << endl;
}

//拷贝构造的第三种场景: 函数传参时会调用拷贝构造
void fun(Test t)
{
	cout << "fun begin" << endl;
	t.test_print();
	cout << "fun end" << endl;
}

void test3(void)
{
	cout << endl;
	cout << endl;
	cout << "test3:xxxxxxxxxxxxxxxxx" << endl;

	Test t1(30);

	Test t2 = t1; //调用一次拷贝构造

	fun(t2);  //这里 t = t2 还会调用一次拷贝构造

	cout << "test3: end xxxxxxxxxxxxxxxxxx" << endl;

}


//拷贝构造的第四种场景: 需要用几个测试函数来说明

Test return_obj(void)
{
	cout << "return_obj begin" << endl;
	Test t1(40);
	cout << "return_obj end" << endl;
	return t1;  //这里会返回一个新的匿名对象,所以会调用匿名对象的拷贝构造函数
}

//return_obj()返回一个新的匿名对象,所以会调用一次拷贝构造函数
void test4_1(void)
{	
	cout << endl;
	cout << endl;
	cout << "test4_1:xxxxxxxxxxxxxxxxx" << endl;
	return_obj();
	cout << "test4_1: end xxxxxxxxxxxxxxxxxx" << endl;

}

//如果⽤匿名对象 初始化 另外⼀个同类型的对象,	匿名对象 转成有名对象
void test4_2(void)
{
	cout << endl;
	cout << endl;
	cout << "test4_2:xxxxxxxxxxxxxxxxx" << endl;

	Test t1 = return_obj();
	t1.test_print();

	cout << "test4_2: end xxxxxxxxxxxxxxxxxx" << endl;
}

//如果⽤匿名对象 赋值给 另外⼀个同类型的对象,	匿名对象 被析构
void test4_3(void)
{
	cout << endl;
	cout << endl;
	cout << "test4_3:xxxxxxxxxxxxxxxxx" << endl;
	Test t1(43);

	t1 = return_obj();

	t1.test_print();

	cout << "test4_3: end xxxxxxxxxxxxxxxxxx" << endl;

}



int main()
{
	test1();
	test2();
	test3();

	test4_1();
	test4_2();
	test4_3();


	return 0;
}


运行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KiranWang

一起努力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值