首頁  >  文章  >  後端開發  >  如何從多型基底類別指標建立衍生類別實例:克隆方法和 CRTP 習慣用法指南

如何從多型基底類別指標建立衍生類別實例:克隆方法和 CRTP 習慣用法指南

Susan Sarandon
Susan Sarandon原創
2024-10-27 00:21:30126瀏覽

How to Create Derived Class Instances from a Polymorphic Base Class Pointer:  A Guide to Clone Methods and the CRTP Idiom

從指向多型基底類別的指標建立衍生類別實例

嘗試建立衍生類別實例的副本時會出現此問題從指向其多態性基底類別的指標。簡單的方法涉及大量類型檢查和動態轉換,檢查每個潛在的派生類型並使用 new 運算子。不過,還有更完善的解決方案。

關鍵是在基底類別中合併一個虛方法 Base*clone() const = 0;。然後,每個衍生類別必須重寫此方法以建立特定的克隆。例如:

<code class="cpp">class Base {
  virtual ~Base();
  virtual Base* clone() const = 0;
};
class Derived1 : public Base {
  virtual Base* clone() const override { return new Derived1(*this); }
};
class Derived2 : public Base {
  virtual Base* clone() const override { return new Derived2(*this); }
};</code>

透過在基底指標上呼叫clone(),可以得到特定衍生類別的新實例。這種簡化的方法消除了型別檢查或動態轉換的需要,提高了程式碼的清晰度和效率。

但是,如果您希望避免程式碼重複,請考慮利用 CRTP(奇怪的重複模板模式)習慣用法。模板類別可以定義如下:

<code class="cpp">template <class Derived>
class DerivationHelper : public Base {
public:
  virtual Base* clone() const override {
    return new Derived(static_cast<const Derived&>(*this));
  }
};

class Derived1 : public DerivationHelper<Derived1> { ... };
class Derived2 : public DerivationHelper<Derived2> { ... };</code>

該模板類別在被派生類別繼承時,為 Clone() 方法提供必要的實現,從而無需在每個派生類別中單獨重寫.

以上是如何從多型基底類別指標建立衍生類別實例:克隆方法和 CRTP 習慣用法指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn