[英]How is the copy constructor being invoked from derived class copy constructor?
我有一個下面的程序,我想知道基類的復制構造函數是如何調用的。
#include <iostream>
using namespace std;
class Base
{
int a;
public:
Base(int xinput):a(xinput)
{
cout<<"Base Ctor:" << a<<endl;
counter++;
}
Base(const Base &obj)
{
a=obj.a;
cout<<"base copy ctr:"<<a<<endl;
counter++;
}
void printcounter()
{
cout<<"Base counter:"<<counter<<endl;
}
virtual ~Base()
{
cout<<"Base Dtor:"<<a<<endl;
counter--;
}
protected:
static int counter;
};
class Derived:public Base
{
int b;
public:
Derived(int xinput,int yinput):Base(xinput),b(yinput)
{
cout<<"Derived Ctor:" << b<<endl;
counter++;
}
void printcounter()
{
cout<<"Derived counter:"<<counter<<endl;
}
~Derived()
{
cout<<"Derived Dtor:" <<b<<endl;
counter--;
}
};
int Base::counter = 0;
Derived d(22,22);
int main()
{
{
Derived D(d);
Base *bptr = new Derived(d);
bptr->printcounter();
delete bptr;
d.printcounter();
}
d.printcounter();
return 0;
}
輸出如下。
Base Ctor:22
Derived Ctor:22
base copy ctr:22 //Why is base copy Ctor invoked
base copy ctr:22
Base counter:4
Derived Dtor:22
Base Dtor:22
Derived counter:2
Derived Dtor:22
Base Dtor:22
Derived counter:0
Derived Dtor:22
Base Dtor:22
由於我沒有在派生類中定義復制構造函數,所以調用了隱式復制構造函數。 但是如何從那里調用 Base 類的復制構造函數。 有人可以告訴內部機制。
由於我沒有在派生類中定義復制構造函數,所以調用了隱式復制構造函數。
正確的。
但是如何從那里調用 Base 類的復制構造函數。
不清楚你所說的“如何”是什么意思。 隱式復制構造函數復制所有子對象。 這包括基礎子對象。
我找到了我正在尋找的答案。
由於派生類沒有顯式的復制構造函數,編譯器定義了它自己的復制構造函數,並且這個復制構造函數有一個初始化列表,在那里調用復制構造函數。
class A
{
public:
int a;
A(int x){cout<<"A::Default ctr"<<endl;}
A(const A& obj){cout<<"A::copy Ctr"<<endl;}
};
class B:public A
{
public:
B(int x):A(x){cout<<"B::Default ctr"<<endl;}
B(const B& obj):A(obj)
{cout<<"B::copy Ctr"<<endl;}
};
int main()
{
B bobj(10);
B b1obj(bobj);
}
在上面的代碼中,如果刪除 B 類復制構造函數的初始化列表中存在的 A(obj),則會出現編譯錯誤。 因此很明顯,當您有任何變量需要作為初始化的一部分傳遞到基類構造函數時,派生類的隱式復制構造函數也提供了一個初始化列表,其中調用基類復制構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.