![](/img/trans.png)
[英]how to implement movable overloads without violating the DRY principle in C++?
[英]C++ mostly redundant default and parameterized constructors violating DRY
(在Visual Studio中使用C ++)
我有以下默認構造函數用於創建一個太空船對象:
Ship() // default constructor
{
name = "[ship unnamed]";
length = 1000;
width = 500;
power = 100;
vector<int> temp = { 100, 100 }; // { current health, maximum health}
bridge = temp;
sensor_arrays.push_back(temp); // 2 sensor arrays
sensor_arrays.push_back(temp);
for (int i = 0; i < 12; i++) // create 12 each
{
lasers.push_back(temp);
heavy_lasers.push_back(temp);
strike_fighters.push_back(temp);
strike_bombers.push_back(temp);
}
}
然后我有以下參數化構造函數用於創建給定名稱的船:
Ship(string custom_name)
{
name = custom_name;
length = 1000;
width = 500;
power = 100;
vector<int> temp = { 100, 100 }; // { current health, maximum health}
bridge = temp;
sensor_arrays.push_back(temp); // 2 sensor arrays
sensor_arrays.push_back(temp);
for (int i = 0; i < 12; i++) // create 12 each
{
lasers.push_back(temp);
heavy_lasers.push_back(temp);
strike_fighters.push_back(temp);
strike_bombers.push_back(temp);
}
}
只有一條線路發生了變化,因此這似乎違反了DRY。
我可以使用默認構造函數然后手動更改我需要的內容,但是我希望有一個或多個參數化構造函數而不重復相同的代碼行。 有辦法做到這一點嗎?
您可以使用以下其中一項:
explicit Ship(const std::string& custom_name = "[ship unnamed]") {/*your code*/}
要么
Ship() : Ship("[ship unnamed]") {} // delegate constructor, require C++11
explicit Ship(const std::string& custom_name) {/*your code*/}
感謝@克里斯的回答,我實現描述的初始化列表在這里 。
解決方案:(原始代碼有問題)
Ship(string custom_name) : Ship()
{
name = custom_name;
/*length = 1000;
width = 500;
power = 100;
vector<int> temp = { 100, 100 };
bridge = temp;
sensor_arrays.push_back(temp); // 2 sensor arrays
sensor_arrays.push_back(temp);
for (int i = 0; i < 12; i++) // create 12 each
{
lasers.push_back(temp);
heavy_lasers.push_back(temp);
strike_fighters.push_back(temp);
strike_bombers.push_back(temp);
}*/
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.