gpt4 book ai didi

C++ moSTLy 冗余默认和参数化构造函数违反 DRY

转载 作者:行者123 更新时间:2023-11-30 02:45:12 32 4
gpt4 key购买 nike

(在 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*/}

关于C++ moSTLy 冗余默认和参数化构造函数违反 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709162/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com