首页 > 解决方案 > 是否有任何规则反对将多个参数放入 mutator 中?

问题描述

我需要我的 mutator 在我的构造函数中调用一个不同的函数,之后随时调用另一个函数,所以我想把一个 bool 作为第二个参数来区分,如下所示:

void SetName(const char* name, bool init)
{
     init ? this(name) : that(name);
}

这是违反惯例还是什么?我应该使用两个单独的突变器吗?

标签: c++conventionsmutators

解决方案


它允许您犯错误,而可以在编译时防止该错误。例如:

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

推荐阅读