0
点赞
收藏
分享

微信扫一扫

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

诗远 2022-02-12 阅读 73

时机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 条评论