为什么在程序中调用这个拷贝构造函数?

Tom*_*Xue 0 c++

#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");
}
Run Code Online (Sandbox Code Playgroud)

运行结果如下:

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

我不明白为什么withCC(withCC&)作为输出的一部分给出.我想composite c2 = c;导致copy-constructor被执行.但是如下所示,WITHCCclass composite为什么会调用它来处理这个拷贝构造函数?谢谢!

Ale*_*Dan 7

拷贝构造函数withCC(withCC&)被调用,因为默认的拷贝构造函数composite会调用所有的拷贝构造函数的它的成员数据.由于您有一个withCC对象作为类中的成员数据composite,因此将withCC(withCC&)调用复制构造函数.