copy constructor的一些疑问

//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。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值