1

I am implementing a class and I have a function that does things using lots of variables that need to be declared and initialised.

I'd like the variable declarations not to clutter the function and do something like:

doFunction(){
  declare();

  //Do things with variables declared in declare()
}
void declare(){
  //declare lots of variables here
}

This does not work as the variables are scoped to declare() and aren't seen by doFunction(). What's a sensible way to handle this problem?

4

3 回答 3

2

由于您声明的每个变量都必须分配一个值,因此您应该将声明与初始化结合起来。换句话说,而不是

int x;
double y;
std::string z;
x = 1;
y = 2.0;
z = "3";

做这个:

int x = 1;
double y = 2.0;
std::string z("3");

这几乎是你可以用本地人推动这种方法的程度:声明变量是函数体的重要组成部分,你不能(并且可以说不应该)将它移动到远程位置。

您还可以将成员函数移动到嵌套的私有类中,将局部变量移动到类中,并在那里进行计算:

class specialCalc {
    int x;
    double y;
    std::string z;
    specialCalc() : x(1), y(2.0), z("3") {}
public:
    int calculate() {
        ...
    }
};

void doFunction() {
     specialCalc calc;
     cout << calc.calculate() << endl;
}

PS:我故意不提及基于预处理器的解决方案,因为它们会对可读性产生负面影响。

于 2012-11-01T13:06:55.977 回答
1

我并不是真的提倡这一点,但是:

struct Declare
{
    int x;
    float y;
    char z;
    vars() :x(1),y(3.14),z('z') {}
};

void doFunction()
{
    Declare vars;
    // use vars.x, vars.y and vars.z as your variables
}
于 2012-11-01T13:12:55.113 回答
0

您有多种选择:

1)克服它。如果您需要大量变量,您将需要忍受需要在某处声明它们的事实。

2) 将它们作为成员变量放入类或结构中,以便您可以在 .h 文件中声明它们,它们在 .C/.cpp 文件中将不可见。

3)将它们聚合成一个数组,只声明数组并在for()循环或其他东西中初始化它们。这只有在它们都是相似的类型并且你不做愚蠢的事情时才有效,比如“索引 4”是我的“计数器对象”,而“索引 5”是我要打印到的“东西”屏幕”,然后您就失去了与变量本身关联的名称,这在以后阅读代码时非常有用(当然)。

4)将它们放在其他地方的定义语句中:

#define MYVARS int a; char b[1024]; ...

void funstuff() {
    MYVARS
}

5) 修改 IDE 以便在您查看代码时隐藏/折叠变量声明。

请注意,在所有这些选择中,数字 1 仍然可能是正确答案 :-)

于 2012-11-01T13:38:06.870 回答