c++ - 是否有任何规则反对将多个参数放入 mutator 中?
问题描述
我需要我的 mutator 在我的构造函数中调用一个不同的函数,之后随时调用另一个函数,所以我想把一个 bool 作为第二个参数来区分,如下所示:
void SetName(const char* name, bool init)
{
init ? this(name) : that(name);
}
这是违反惯例还是什么?我应该使用两个单独的突变器吗?
解决方案
它允许您犯错误,而可以在编译时防止该错误。例如:
Example example;
example.SetName("abc", true); // called outside the constructor, `init == true` anyway
为了防止这种情况,只需更换您的
struct Example {
Example() { SetName("abc", true); }
void SetName(const char* name, bool init) { init ? foo(name) : bar(name); }
};
和
struct Example {
Example() { foo("abc"); }
void SetName(const char* name) { bar(name); }
};
测试:
Example example; // calls the for-the-constructor version
example.SetName("abc"); // calls the not-for-the-constructor version
example.SetName("abc", true); // obviously, doesn't compile any more
推荐阅读
- swift - macOS Swift-App 写权限问题?
- c - 尽管存在 libgd.a,但由于未定义的引用,我无法交叉编译使用 libgd 的简单程序
- flutter - removeWhere in list of files
- python - 尝试使用 BeautifulSoup 过滤结果但结果保持不变?
- javascript - 如何在 Javascript 中加载 url 以及保存的 Cookie?
- c++ - 是否允许在函数模板的显式特化中扣除多个模板参数?
- angular - angular-cli 全局全新安装后未找到 @angular-devkit/core 模块
- email - 在不使用表格转换器的情况下从 Google 表格发送电子邮件作为表格
- javascript - Javascript Date() 在 IE 中返回无效日期(版本 11)
- javascript - 循环遍历每个元素并将值添加到新对象。将这些对象添加到数组并访问它们的值