拷贝构造函数

  • 当函数调用,值传递对象时(参数或返回值)调用拷贝构造函数。
  • 默认拷贝构造函数为位拷贝
  • 例子:
#include "stdafx.h"
#include <iostream>
using namespace std;

class CExample
{
public:	
	CExample();
	CExample(int i);
	CExample(const CExample &example);//copy constructor
	~CExample();
private:
	int i;
};

CExample::CExample()
{
	i = 0;
	cout<<"constructor()"<<endl;
}

CExample::CExample(int j)
{
	i = j;
	cout<<"constructor(int)"<<endl;
}

CExample::~CExample()
{
	cout<<"destructor()"<<endl;
}

CExample::CExample(const CExample &example)
{
	cout<<"copy constructor"<<endl;
}

void fun1(CExample obj)//call copy constructor
{ } CExample fun2() { CExample obj; return obj;//call copy constructor
} int _tmain(int argc, _TCHAR* argv[]) { { CExample tmp1; CExample tmp2(1); CExample tmp3 = tmp2;//call copy constructor cout<<"---------------fun1--------------"<<endl; fun1(tmp3); cout<<"+++++++++++++++fun1++++++++++++++"<<endl; cout<<"---------------fun2--------------"<<endl; fun2(); cout<<"+++++++++++++++fun2++++++++++++++"<<endl; } system("pause"); return 0; }

输出结果:

注:若不希望类用户进行拷贝构造函数的调用(即使是默认的拷贝构造函数),可以将拷贝构造函数声明为private。

posted @ 2011-04-09 16:10  iThinking  阅读(290)  评论(0)    收藏  举报