[英]C++ creating a copy constructor for a class with a reference member variable
我有一個類ModelRecorder
與包含參考modelRef_
到另一個類OpModel。
class ModelRecorder : public CompositionalModel //This is an abstract base class
{
OpModel& modelRef_;
};
當一個實例ModelRecorder
創建和modelRef_
被initalized。 很好,我無法理解。
我將如何為ModelRecorder
寫一個副本構造函數,以便如果創建另一個實例,則引用成員modelRef_
將與先前創建的OpModel對象一起初始化?
請注意, CompositionalModel
是抽象的基類。
在另一個類中,函數可以返回對基類的CompositionalModel
的引用。 我知道返回較窄的基類是一個很好的OOP。
例如CompositionalModel& recordedModel();
我想將此對基類的引用傳遞給復制構造函數。
我嘗試了這個,但它給出了錯誤,這是正確的modelRef
在取消引用的類ModelRecorder
。
錯誤:“常量類mv :: CompositionalModel”沒有名為“ modelRef_”的成員
mv::ModelRecorder::ModelRecorder(const CompositionalModel& arg) : CompositionalModel{static_cast<const ModelRecorder&>(arg)}, modelRef_{arg.modelRef_}
{
}
有兩種方法:
第一種方法-使編譯器為您完成此操作:
ModelRecorder(const ModelRecorder&) = default;
第二種方法-自己實施:
ModelRecorder(const ModelRecorder& arg)
:CompositionalModel{arg}, modelRef_{arg.modelRef_} {}
請注意,由於我們要處理引用, 因此必須使用成員初始化器列表。 上面的代碼和這個之間的區別:
ModelRecorder(const ModelRecorder& arg)
:CompositionalModel{arg} {
modelRef_ = arg.modelRef_;
}
是后者不會初始化引用 。 它違反了規則,因為引用必須初始化,以后再不分配。 我最好的建議是堅持使用簡單的方法,因為使用它的可能性最小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.