//A.h
#include <iostream>
using namespace std;
class A
{
public:
A():iptr(NULL)
{
cout << "constructor: A()" << endl;
}
A(int ix)
{
iptr = new int;
*iptr = ix;
cout << "constructor: A(int ix)" << endl;
}
//copy constructor
A(const A& a)
{
cout << "copy constructor of class A" << endl;
iptr = new int;
*iptr = *a.iptr;
}
~A()
{
cout << "destructor of class A" << endl;
delete iptr;
}
int getNum()
{
return *iptr;
}
private:
int *iptr;
};
A AddA(A a1, A a2)
{
cout << "function: AddA()" << endl;
A *aPtr = new A(a1.getNum() + a2.getNum());
return *aPtr;
}
//main.cpp
#include "A.h"
int main(void)
{
A a1(5);
A a2 = a1;
A a3 = 6;
A a4 = AddA(a2, a3);
getchar();
return 0;
}
输出结果为 //行数是我自己加上去的,为了方便说明
1 constructor: A(int ix)
2 copy constructor of class A
3 constructor: A(int ix)
4 copy constructor of class A
5 copy constructor of class A
6 function: AddA()
7 constructor: A(int ix)
8 copy constructor of class A
9 destructor of class A
10 destructor of class A
第一行输出对应着 A a1(5); 普通的构造函数
第二行输出对应着 A a2 = a1;则是因为这是复制初始化,需要调用复制构造函数
第三行输出对应着 A a3 = 6;问题出在这里,按照我对c++ primer里面的理解,这时候应该是先调用A(int ix)构造一个临时对象,然后再调用copy constructor,将这个临时对象复制到正在创建的a3中,但是只打印出了第三行。
第四行~第十行,是因为函数调用,引起的对形参的一些复制初始化,和返回对象的复制初始化。
求大牛解答,我用的是visual studio 2005。