C++拷贝构造函数的4种调用时机_2022

时机1:

Test t2 = t1;//等号法

时机2:

Test t3(t1);//括号法

时机3:

void objTest1(Test t);//对象做函数参数

时机4:

Test objTest2();//函数的返回值是一个对象

#include <iostream>

using namespace std;

class Test
{
public:
	Test()
	{
		a = 0;
		b = 0;
		cout << "no parameter construct." << endl;
	}
	Test(int a)
	{
		this->a = a;
		b = 0;
		cout << "one parameter construct." << endl;
	}
	Test(int a, int b)
	{
		this->a = a;
		this->b = b;
		cout << "two parameter construct." << endl;
	}
	Test(const Test& obj)
	{
		this->a = obj.a;
		this->b = obj.b;
		cout << "copy construct." << endl;
	}
	~Test()
	{
		cout << "destruct." << endl;
	}
public:
	void printT()
	{
		cout << "a=" << a << " " << "b=" << b << endl;
	}
private:
	int a;
	int b;
};

void objplay1()
{
	Test t1;
	Test t2(1);
	Test t3(2, 3);
}

void objplay2()
{
	Test t1 = (3, 4, 5, 6);
	t1.printT();
}

void objplay3()
{
	Test t1(1, 2);//
	Test t2(t1);//1-->
	Test t3 = t1;//2-->
}

void objTest1(Test t)
{
	t.printT();
}

void objTest2(Test& t)
{
	t.printT();
}

Test objTest3(Test& obj)
{
	return obj;
}

Test& objTest4(Test& obj)
{
	Test t(1, 8);
	return t;
}

void objplay4()
{
	Test t1(1, 3);
	objTest1(t1);
}

void objplay5()
{
	Test t1(1, 3);
	objTest2(t1);
}

void objplay6()
{
	Test t1(1, 3);
	objTest3(t1);
}

void objplay7()
{
	Test t1(1, 3);
	objTest4(t1);
}

int main()
{
	objplay7();

	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值