简体   繁体   English

什么时候应该在头文件中声明一个变量?

[英]When should a variable be declared in the header file?

I have this class with a lot of functions (around 30) and each function declares a new integer value that is used to store the value from the conversion of a string from the stack to an integer.我有这个类有很多函数(大约 30 个),每个函数声明一个新的整数值,用于存储字符串从堆栈转换为整数的值。 This means I keep declaring new integers so many times in the same class.这意味着我在同一个类中多次声明新整数。

Here is an example of a function that declares these integers:下面是一个声明这些整数的函数示例:

void Interpreter::add()
{
    val1 = std::stoi(stack.back());
    stack.pop_back();
    val2 = std::stoi(stack.back());
    stack.pop_back();

    stack.push_back(std::to_string(val1 + val2));
}

class Interpreter 
{
private:
    int val1, val2;

}

My question is: is it better to declare these variables only once in the header file and then re-use them in each function?我的问题是:在头文件中只声明一次这些变量然后在每个函数中重新使用它们是否更好?

I'd like to know if there is some kind of convention on this matter.我想知道在这个问题上是否有某种约定。

Don't use member variables just to save on typing – you're going to encounter bugs that are incredibly hard to find.不要仅仅为了节省输入而使用成员变量——你会遇到难以发现的错误。

Add a little abstraction,添加一点抽象,

int Interpreter::pop() 
{ 
    // Add error handling here.
    int i = std::stoi(stack.back());
    stack.pop_back();
    return i;
}

void Interpreter::push(int i)
{
    stack.push_back(std::to_string(i));
}

and then you can write然后你可以写

void Interpreter::add()
{
    push(pop() + pop());
}

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

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