![](/img/trans.png)
[英]Which is the better approach to initialise the base class member while creating derive class object?
[英]Calling copy constructor of base class while creating object of derive class by copying another object of derive class
class base {};
class der : public base{};
der d1;
der d2(d1);
該語句調用類庫的默認構造函數,然后復制claas der的構造函數。 我的問題是,為什么C ++在通過復制派生類的另一個對象創建派生類的對象時沒有提供調用基類的副本構造函數的功能
該語句調用類庫的默認構造函數,然后復制claas der的構造函數。
不,不是。
我的問題是,為什么C ++在通過復制派生類的另一個對象創建派生類的對象時沒有提供調用基類的副本構造函數的功能
是的
我不知道您是如何得出結論的,即在構造d2
調用了基本默認構造函數,但事實並非如此。 該合成基礎拷貝構造函數被調用,如您所願。
這真的很容易測試 :
struct base {
base() { cout << "*B"; }
base(base const& b) { cout << "!B"; }
~base() { cout << "~B"; }
};
struct der : base {};
int main() {
der d1;
der d2(d1);
}
// Output: *B!B~B~B
派生類的復制構造函數調用基類的默認構造函數。
下面的示例程序進行了演示。
#include <iostream>
using namespace std;
class Base
{
public:
Base(){ cout<<"Base"<<endl; }
Base(int i){ cout<<"Base int "<<endl; }
Base(const Base& obj){ cout<<"Base CC"<<endl; }
};
class Derv : public Base
{
public:
Derv(){ cout<<"Derv"<<endl; }
Derv(int i){ cout<<"Derv int "<<endl; }
Derv(const Derv& obj){ cout<<"Derv CC"<<endl; }
};
int main()
{
Derv d1 = 2;
Derv d2 = d1; // Calls the copy constructor
return 0;
}
該語句調用類庫的默認構造函數,然后復制claas der的構造函數。
不,不是的。
第一行調用der
類的默認構造,而der
調用類base
的默認構造函數。 第二行調用der
類的copy構造函數,因為您要將一個der
實例復制到另一個實例。
編譯器生成的copy-constructor將調用基類的copy構造函數。
您可能已經為der
添加了用戶定義的副本構造函數。 在這種情況下,必須顯式調用基類的副本構造函數。
der::der(const der& other): base(other), ... {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.