[英]Why passing derived class type as parameter when calling base class copy constructor (C++)?
[英]C++ Base constructor calling with parameter that will be constructed in the derived constructor
問題1)
class Base {
Base(std::string name);
virtual std::string generateName();
}
class Derived : Base {
Derived();
virtual std::string generateName();
}
這里有一個問題:
將在generateName()上調用什么方法?
Derived :: Derived : Base(generateName()) {
//what method will be called on generateName() ?
}
問題2)
我該怎么做? 如果默認構造函數必須接受一個參數,但我需要在Derived構造函數中生成該參數?
首先,解決方案:使用靜態成員函數或非成員函數。
至於行為,將調用Derived::generateName()
。 C ++標准中定義此行為的長句說(C ++ 03 12.7 / 3):
當直接或間接地從構造函數(包括來自數據成員的mem-initializer)或析構函數調用虛函數時,調用所適用的對象是正在構造或銷毀的對象,調用的函數是一個在構造函數或析構函數自己的類或其基礎中定義的,但不是在從構造函數或析構函數的類派生的類中重寫它的函數,或者在最派生對象的其他基類之一中重寫它。
因為在虛擬調用時執行的構造函數是Derived
構造函數,所以調用Derived::generateName()
。
現在刪除的答案正確地提到了Scott Meyers的一篇文章,該文章建議“在施工或銷毀期間永遠不要調用虛函數”。 被稱為覆蓋者的規則是復雜且難以記住的。
拿兩個......
我在基類初始化程序和兩個構造函數中調用了generateName()
。 輸出讓我感到困惑:
Derived (called from Derived's Base initializer)
Base (called from Base ctor)
Derived (called from Derived ctor)
我從來沒有想過一個類可以從一個派生變為一個基礎,然后再回到一個構造序列中的派生。 你每天學習新的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.