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. 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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.