0
#include <iostream>
#include <string.h>

using namespace std;

class withCC
{
public:
    withCC() {}
    withCC(const withCC&) {
        cout<<"withCC(withCC&)"<<endl;
    }
};

class woCC
{
    enum {bsz = 100};
    char buf[bsz];
public:
    woCC(const char* msg = 0) {
        memset(buf, 0, bsz);
        if(msg) strncpy(buf, msg, bsz);
    }
    void print(const char* msg = 0)const {
        if(msg) cout<<msg<<":";
        cout<<buf<<endl;
    }
};

class composite
{
    withCC WITHCC;
    woCC WOCC;
public:
    composite() : WOCC("composite()") {}
    void print(const char* msg = 0) {
        cout<<"in composite:"<<endl;
        WOCC.print(msg);
    }
};

int main()
{
    composite c;
    c.print("contents of c");
    cout<<"calling composite copy-constructor"<<endl;
    composite c2 = c;
    c2.print("contents of c2");
}

运行结果如下:

$ ./a.out 
in composite:
contents of c:composite()
calling composite copy-constructor
withCC(withCC&)
in composite:
contents of c2:composite()

而且我不明白为什么withCC(withCC&)作为输出的一部分给出。我猜composite c2 = c;会导致执行复制构造函数。但是如下图,WITHCC是的一部分class composite,为什么会调用它来处理这个拷贝构造函数呢?谢谢!

4

3 回答 3

7

复制构造函数withCC(withCC&)被调用是因为它的默认复制构造函数composite将调用其成员数据的所有复制构造函数。并且由于您有一个withCC对象作为类中的成员数据,因此调用composite了复制构造函数。withCC(withCC&)

于 2013-01-01T15:21:39.277 回答
2

复制构造函数被调用

  • 当实例化一个对象并用另一个对象的值初始化它时,或者
  • 每当您通过值将对象作为参数传递给函数或
  • 从函数中按值返回对象

类的默认复制构造函数composite将调用其成员的复制构造函数,这就是withCC(withCC&)打印的原因。

于 2013-01-01T15:22:26.173 回答
1

语句复合 c2 = c; 将尝试通过复制构造函数复制对象,但类复合没有用户定义的复制构造函数,因此将在您的情况下使用编译器的默认复制构造函数。并且您还想通过创建复合材料来构造WOCC对象,因此对于WOCC构造,用户定义 with cc 的复制构造函数被调用

于 2013-01-01T15:35:05.613 回答