簡體   English   中英

對孩子使用父類構造函數

[英]Use parent class constructor for child

因此,我想擁有一個Child類,該類具有其父類的所有構造函數。 這在C ++中可能嗎? 我曾嘗試using語句,但無法正常工作。 到目前為止,這是我得到的:

struct Base{
    Base(int i){
        std::cout << "Construcetd a base with " << i << std::endl;
    }


};


struct Child : public Base{
    using Base::Base;

};




int main(){

    Child c(1);
}

我得到的錯誤:

error C2664: 'Child::Child(const Child &)' : cannot convert argument 1 from 'int' to 'const Child &'

哦,我在用Visual Studio 2013

繼承構造函數是C ++ 11語言功能,

struct A { A(int); };
struct B: A { using A::A; }; // defines B::B(int)
B b(42); // OK

但是,如msdn中所述 ,Visual Studio 2013不支持它。

正如你可以看到這里 ,繼承構造尚未由Microsoft Visual Studio支持C ++ 11功能。

您發布的代碼是正確的,並且可以在C ++ 11編譯器上正常工作。

編譯器嘗試調用默認的Child構造函數(不帶參數)。 因此,要使代碼正常工作,您需要提供顯式的構造函數:

struct Child : public Base{
    using Base::Base;
    Child(int i):Base(i) {}

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM