// MyClass.h
namespace MyNamespace {
static const double GasConstant = 1.987;
class MyClass
{
// constructors, methods, et开发者_开发技巧c.
};
}
I previously had GasConstant declared within the MyClass declaration (and had a separate definition in the source file since C++ does not support const
initialization of non-integral types). I however need to access it from other files and also logically it seems like it should reside at the namespace level.
My questions is, what effect does static const
have in this case? Clearly const
means I can't assign a new value to GasConstant, but what does a static member at the namespace mean. Is this similar to static at file scope, where the member is not accessible outside of the unit?
The use of static
at namespace scope is was* deprecated in C++. It would normally only ever be seen in a source file, where its effect is to make the variable local to that source file. That is, another source file can have a variable of exactly the same name with no conflict.
In C++, the recommended way to make variables local to the source file is to use an anonymous namespace.
I think it's fair to say the static
in the header in your code is simply incorrect.
*As pointed out by Tom in the comments (and in this answer), the C++ committee reversed the decision to deprecate static
use at file scope, on the basis that this usage will always be part of the language (e.g. for C compatibility).
MSDN says:
When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).
Remember that including header files means to replace the "#include"-directive with the actual code of the header file. So, the static variables will be visible only in the ".cpp" (which is compiled) file that includes the two header files.
So each "cpp"-file including the headers will have it's own static variable.
If this is a header file, then static
has no effect in this case. const
objects already have internal linkage by default in C++, so whether you declare it with static
or without static
makes no difference whatsoever.
I assume you simply moved the declaration from the class into the namespace. But static
has totally different meaning in the context of the class declaration and in the context of namespace. Inside the class, you needed static
. In the namespace the static
is superfluous.
精彩评论