c++ - 在其他重载中重用重载

标签 c++

如果我有 setter 函数重载

void setDamageRange(const Range& r);
void setDamageRange(int min, int max);

而且我能够在另一个中使用其中一个重载

void Weapon::setDamageRange(const Range& r)
{
    setDamageRange(r.min, r.max);
}

void Weapon::setDamageRange(int min, int max)
{
    mDamageRange.min = min;
    mDamageRange.max = max;
}

我应该这样做吗?或者我应该像这样再次进行所有有效性检查和分配

void Weapon::setDamageRange(const Range& r)
{
    mDamageRange = r;
}

void Weapon::setDamageRange(int min, int max)
{
    mDamageRange.min = min;
    mDamageRange.max = max;
}

?

我的直觉告诉我,出于重用代码的目的,我应该选择第一个备选方案,因为这通常是很好的做法。但与此同时,感觉它在某种程度上使它变得困惑,特别是如果我要提供更多的函数重载,因为其中只有一个是“控制”函数。

如果我认为我并不真的需要“控制”函数并将其删除,我就必须重写所有其他重载的代码。

最佳答案

should I [call one overload from the other]?

当然!这是重用代码的绝佳方式。

Or should I do all validity checking and assignment again

通常,这会违背 Don't Repeat Yourself原则,因为相同的验证(如果有的话)必须进入两个地方。

关于c++ - 在其他重载中重用重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32288715/

相关文章:

c++ - 这不是在 C++ 中使用 bool 运算符吗?

c++ - qt 5 QMediaPlayer错误: Gstreamer unable to play

c++ - 使用两个透明图像的深度测试会导致奇怪的伪像

c++ - 在连续的内存位置存储字符串文字

c++ - 用模板函数计算中值

c++ - 使用 iostream 堆栈内存

c++ - Visual Studio Code C/Cpp : Edit configurations does not open c_cpp_properties. json

c++ - 为什么我收到错误: “there is more than one default constructor” ?

c++ - 如果我没有收到来自客户端的消息,如何每 20 秒打印一次日期时间

c++ - 继承的类数据成员