您将如何修复以下传递过多参数的错误代码?
void helper1(int p1, int p3, int p5, int p7, int p9, int p10) {
// ...
}
void helper2(int p1, int p2, int p3, int p5, int p6, int p7, int p9, int p10) {
// ...
}
void foo(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8,
int p9, int p10) {
helper1(p1, p3, p5, p7, p9, p10);
helper2(p1, p2, p3, p5, p6, p7, p9, p10);
}
我看到两种不同的方法:
方法1:将所有函数放在一个类中
class Foo {
private:
int p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;
void helper1() {}
void helper2() {}
public:
void foo() {
helper1();
helper2();
}
// add constructor
};
方法2:只需将参数作为类传递
struct FooOptions {
int p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;
};
void helper1(const FooOptions& opt) {
// ...
}
void helper2(const FooOptions& opt) {
// ...
}
void foo(const FooOptions& opt) {
helper1(opt);
helper2(opt);
}
这些方法的优点和缺点是什么?
方法 1 的一个优点是——如果你将helper
函数设为虚拟——你可以继承和重载它们,从而增加灵活性。但是,在我的情况下(在我给出的玩具迷你示例之外),这些助手通常是模板化的,所以它们无论如何都不能是虚拟的。
方法 2 的一个优点是辅助函数也可以很容易地从其他函数中调用。
(这个问题是相关的,但没有讨论这两种选择。)