#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
的一部分,爲什麼它會被調用來處理這個拷貝構造函數?謝謝!
構造? –
@AshRj:我不認爲這是相當重複的:這裏用戶想知道複製構造函數w.r.t的行爲。組成,而不是繼承。 –
@MFFooz我的錯誤。已移除鏈接。 – asheeshr