// copyconstructor.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A(int num)
{
cout<<"the constructor of A is called"<<endl;
m_num = num;
}
A(A& source)
{
cout<<"the copy constructor of A is called"<<endl;
m_num = source.m_num;
++source.m_num;
}
A operator = (A source)
{
//在进入函数之前,会调用一次copy constructor,情况是以object作为参数传入,此时因为是传值
//所以会调用,如果参数是以引用传入时A& source,就不会调用copy constructor,因为初值已有了
cout<<"the operator = of A is called"<<endl;
m_num = source.m_num;
//此时因为是以object作为返回值,所以会调用copy constructor
cout<<"the operator = of A calling is finished"<<endl;
return source;
}
private:
int m_num;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a(1);
A b(2) ;
b = a; //此时不是以object为另一个object赋初值,所以不会调用copy constructor,而是调用operator =
A c = a; //在这里是以一个object为另一个object赋初值,所以会调用copy constructor
return 0;
}