简体   繁体   English

在 class 方法中初始化变量?

[英]Initialize variables in a class method?

I have a silly question:我有一个愚蠢的问题:

I have a class and in one of its methods I have to do some calculations and I need to declare some variables that are useful to do this.我有一个 class 并且在它的一种方法中我必须进行一些计算,并且我需要声明一些对此有用的变量。 For example:例如:

class Percettrone {
public:
    Percettrone(double NL);
    void fit(double X, double y);
}
.
.
.
void Percettrone::fit(double X, double y)
{
        double delta[50][50];
        double conteggio=0;
        //calculations
}

Is it correct?这是对的吗? Or is it better to declare when I create the class?还是在我创建 class 时声明更好? Moreover I have to call this method lots of time during my programme此外,我必须在我的程序中调用这个方法很多时间

If those variables are affecting the object instance and identifying its state, then you must declare them in the class as attributes.如果这些变量影响 object 实例并识别其 state,那么您必须在 class 中将它们声明为属性。 On the other hand, if they're just helper variables in the function, and you don't need to use them anywhere else, then make them local inside the function as you did in the example.另一方面,如果它们只是 function 中的辅助变量,并且您不需要在其他任何地方使用它们,那么就像您在示例中所做的那样,在 function 中将它们设置为本地变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM