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

//============================================================================
// 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;
}
posted @ 2013-05-08 12:36  helloweworld  阅读(180)  评论(0编辑  收藏  举报