我希望能夠根據以下代碼中通過類建構式接收的條件,以 N 種方式之一(在此示例中 N=2)初始化類成員,但 MainObject 的初始化似乎只是本地(容器)類的建構式。我想知道這種特定模式的最佳實踐是什么。
// in ContainerObject.hpp
class ContainerObject {
public:
MainClass MainObject;
ContainerObject(int type);
}
// in ContainerObject.cpp
ContainerObject::ContainerObject(int type);{
if (type == 0){
MainObject("something", 1, 2);
} else if (type == 1){
MainObject(4, "another thing", "yet another thing");
}
}
我到目前為止想過
- 將主要物件放在堆中
- 定義 N 個類建構式并在“main”/“first”類建構式中遞回呼叫適當的建構式。
請注意,“0”和“1”初始化只是一個例子,可能會有很大的不同。
EDIT1:添加了“;” 編譯 EDIT2 所需:更改了原來的
//...
if (type == 0){
MainObject(0);
} else if (type == 1){
MainObject(1);
}
//...
對于當前的
//...
if (type == 0){
MainObject("something", 1, 2);
} else if (type == 1){
MainObject(4, "another thing", "yet another thing");
}
//...
因為它被誤解為可以通過添加以下內容解決的案例而被稱為重復。
//...
ContainerObject(int type): MainObject(type);
//...
uj5u.com熱心網友回復:
我將這個問題解釋為“如何在成員初始化串列之前/期間執行非平凡邏輯”。
一個很好的方法是將外部物件的建構式引數轉換為子物件的作業委托給一個實用函式:
// in ContainerObject.cpp
#include <stdexcept> // for std::invalid_argument
// Anonymous namespace since main_factory() is only needed in this TU.
namespace {
MainClass main_factory(int type) {
if (type == 0) {
return MainClass("something", 1, 2);
} else if (type == 1) {
return MainClass(4, "another thing", "yet another thing");
}
// N.B. This is one of the scenarios where exceptions are indisputably
// the best way to do error handling.
throw std::invalid_argument("invalid type for MainClass");
}
}
ContainerObject::ContainerObject(int type)
: MainObject(main_factory(type)) {}
uj5u.com熱心網友回復:
每當創建物件時,總是自動呼叫建構式。你永遠不能在任何地方自己呼叫它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341844.html
上一篇:是否有一種方法可以根據另一個變數的隨機化結果來約束類中的隨機變數?
下一篇:用C#制作ASCII碼?
