假设我有一个简单的C++程序.
Function_C()
{
/*pass;*/
}
Function_B()
{
Function_C();
}
Function_A()
{
Function_B();
}
int main()
{
int x,y;
std::cin >> x >> y;
Function_A();
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是:如果我想使用的输入x,并y在Function_C
(比方说做比较),我需要通过x和y到Function_A,然后到Function_B,最后的Function_C,这使我的参数添加到Function_A,并Function_B不仅仅是因为的Function_C.这似乎是坏代码:(
那么,善良的堆栈溢出,谁能提供更好的主意?
这不一定是坏代码 - 甚至有一个名称,它在某种程度上使模式合法化:从上面参数化.(Acknowledge @Paul Evans).它优于使用全局变量.
面向对象的编程可以避免这种情况.基于配方的解决方案
struct Foo
{
int x;
int y;
void Function_C(){/*use x and y*/}
void Function_B(){Function_C();}
void Function_A(){Function_B();}
};
int main(){
int x,y;
std::cin >> x >> y;
Foo f{x, y};
f.Function_A();
}
Run Code Online (Sandbox Code Playgroud)
可能会扩大更好.