#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的一部分,为什么要调用它来处理这个复制构造函数呢?谢谢!
发布于 2013-01-01 23:21:39
由于composite的默认复制构造函数将调用其成员数据的所有复制构造函数,因此调用了复制构造函数withCC(withCC&)。由于在composite类中有一个withCC对象作为成员数据,因此将调用复制构造函数withCC(withCC&)。
发布于 2013-01-01 23:22:26
调用复制构造函数
时
函数中的值返回对象
composite类的默认复制构造函数将调用其成员的复制构造函数,这就是打印withCC(withCC&)的原因。
发布于 2013-01-01 23:35:06
语句复合c2 = c;将尝试通过复制构造函数复制对象,但类复合没有用户定义的复制构造函数,因此在您的情况下将使用编译器的默认复制构造函数。并且您还希望通过创建复合来构造WOCC对象,因此,对于WOCC构造,将调用用户定义的with cc的复制构造函数
https://stackoverflow.com/questions/14111563
复制相似问题