多重繼承 – 建構函式的規則

來源:互聯網
上載者:User

虛基類的子類的子類在多重繼承時,建構函式初始化父類的建構函式將不會將資訊傳給虛基類,但可以顯示調用對應虛基類的建構函式來構造自身對象,從而獲得一個虛基類的對象避免多重繼承的衝突;如果未顯示調用虛基類的建構函式,將自動調用其預設的建構函式。

C++ primer plus 6th

     14. Reusing Code in C++

           New Constructor Rules

SingingWaiter(const Worker & wk, int p = 0, int v = Singer::other)  : Waiter(wk,p), Singer(wk,v) {}  // flawed

The problem is that automatic passing of information would pass wk to the Worker object via two separate paths (Waiter and Singer).
To avoid this potential conflict, C++ disables the automatic passing of information through an intermediate class to a base class if the base class is virtual. Thus, the previous constructor will initialize the panache and
voice members, but the information in the wk argument won’t get to the Waiter subobject. However, the compiler must construct a base object component before constructing derived objects;
in this case, it will use the default Worker constructor.

If you want to use something other than the default constructor for a virtual base class,
you need to invoke the appropriate base constructor explicitly. Thus, the constructor should look like this:

SingingWaiter(const Worker & wk, int p = 0, int v = Singer::other) : Worker(wk), Waiter(wk,p), Singer(wk,v) {}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.