Static Variables in Overloaded Functions
I have a function which does the following:
- When the function is called and passed a true bool value, it sets a static bool value to true
- When the function is called and passed a string, if the开发者_如何学编程 static bool value is set to true, it will do something with that string
Here is my concern -- will a static variable remain the same between two overloaded functions? If not, I can simply create a separate function designed to keep track of the bool value, but I try to keep things simple.
Two overloaded functions are two different functions. Even if each function contains a static bool
with the same identifier, they belong in different scopes and the identifier refers to a distinct variable in each function.
If you need to share state between two functions you are probably better off making a class to encapsulate this state and making the two functions member functions of this class.
No, it creates two separate static variables - one for each function. The name of any C++ function is made op of its apparent name and its parameter types, and the name of the static is (conceptually at least) tacked on to that. Rather than add yet another function, you could consider making the variable static with respect to the class containing the functions, although this does not give you exactly the same behaviour, or place it in an anonymous namespace:
namespace {
int myvar = 0;
}
int f( bool b ) {
return myvar;
}
int f( const string & s ) {
return myvar;
}
To make the functions members of a class:
// a.h
class A {
public:
static int f( bool b ) {
return myvar;
}
static int f( const string & s ) {
return myvar;
}
private:
static int myvar;
};
// a.cpp
int A::myvar = 0;
// main.cpp
#include <iostream>
#include <a.h>
int main() {
std::cout << A::f(false) << A::f( string("foobar") ) << std::endl;
}
The answer is no. There is no reason it should be, since after all we are talking about 2 functions.
Since it's already been demonstrated, I'd like to address the very core of the matter: static
.
static
introduces global state, and global state is evil. It leads to subtle bugs, difficulties to test properly (since a test affects the ones executed after it) and don't even think about going multithreaded there...
Therefore I would really encourages you to avoid the static
entirely. You would then have 2 solutions:
- Make a class with the two overloads as methods, and store state (not static, please)
- Pass the bool as parameter to the methods, out-parameter for the bool overload and in-parameter for the string overload
Pick up whichever is easier to achieve.
精彩评论