是否有任何规则反对在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

最新更新