栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++拷贝构造函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++拷贝构造函数

#include 
using namespace std;





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


运行结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/352699.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号