簡體   English   中英

在C ++ 0x中繼承構造函數

[英]Inheriting constructors in C++0x

可以說,在我們有望成為下一個C ++標准的過程中,我具有以下代碼:

int f(int x) 
{ 
  std::cout << x;
  return x * x; 
}

struct A
{
  A(int x) : m_x(x) {}
  int m_x;
};

struct B : A
{
  using A::A;
  B() : m_y(f(m_x)) {}
  int m_y;
};

int main()
{
  B(5);
}

這會調用B的默認構造函數並輸出5並設置m_y = 25嗎? 還是B的默認構造函數不會運行,並保留m_y未初始化?

如果是后者,不調用B默認構造函數的原理是什么? 很顯然,A(int)B僅繼承初始化A,而使B處於不確定狀態。 為什么C ++選擇簡單的調用B()的默認構造函數來選擇未定義的行為? 它在很大程度上違反了繼承構造函數功能的目的。

編輯:

也許應該允許:

using A::A : m_y(...) { std::cout << "constructing..." << std::endl; ...; }

using A::A; 在派生類中隱式聲明B(int) 這就對了。

程序的其余部分將無法按預期工作。 因為您要使用B(5)調用B(int) B(5) ,所以m_y初始化。

請參閱Bjarne Stroustrup網站上的示例:

struct B1 {
    B1(int) { }
};

struct D1 : B1 {
    using B1::B1; // implicitly declares D1(int)
    int x;
};

void test()
{
    D1 d(6);    // Oops: d.x is not initialized
    D1 e;       // error: D1 has no default constructor
}

http://www2.research.att.com/~bs/C++0xFAQ.html#inheriting

來自同一鏈接的另一個示例:

struct D1 : B1 {
        using B1::B1;   // implicitly declares D1(int)
        int x{0};   // note: x is initialized
    };

    void test()
    {
        D1 d(6);    // d.x is zero
    }

暫無
暫無

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

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