拷贝构造 赋值构造 何时调用

//============================================================================
// Name        : HelloWorldcpp.cpp
// Author      : Lucas
// Version     :
// Copyright   : @Lucas
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string.h>
#include <algorithm>
#include <dos.h>
#include <windows.h>
using namespace std;

class Test
{
public:
	int a;

	Test() {cout << "no parameter" << endl; a = 1;};
	Test(int) {cout << "has parameter" << endl; a = 2;};

	Test& operator= (const Test& test)
	{
		cout << "call operator =" << endl;
		if (&test != this)
		{
			this->a = test.a;
		}

		return *this;
	}

	Test(const Test& test) {cout << "copy constructor" << endl; this->a = test.a;}
};


int main()
{
//	Test t1;					//no parameter
//	cout << t1.a << endl;
//
//	Test t2();					//函数声明。
////	cout << t2.a << endl;	//error
//
//	Test t3(111);				//has parameter
//	cout << t3.a << endl;
//
////	Test t4 = Test;			//error
////	cout << t4.a << endl;
//
//	Test t5 = Test();			//no parameter, copy constructor
//	cout << t5.a << endl;
//
//	Test t6 = Test(444);		//has parameter, copy constructor
//	cout << t6.a << endl;

	Test t7(11);				//has parameter
	Test t8 = t7;				//copy constructor
	cout << t8.a << endl;

//	Test t9(22);				//has parameter
//	Test t10(t9);				//copy constructor
//	cout << t10.a << endl;

	Test t11(33);
	Test t12;
	t12 = t11;				//call operator =
	return 0;
}

原文链接: https://www.cnblogs.com/helloweworld/archive/2013/05/08/3066528.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    拷贝构造 赋值构造 何时调用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/87647

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午11:11
下一篇 2023年2月9日 下午11:12

相关推荐