The static keyword is probably the most confusing keyword in the C++ language. This is because it has different meanings depending on where it is used.
(static很令人迷惑,因为在不同的地方有不同的用途)
You know, local variables (which have block scope) and global variables (which have program scope).
By default, local variables have automatic duration, which means they are destroyed when the block they are declared in goes out of scope.
(介绍scope -- program scope & block scope。)
(另一种跟static相关的scope -- file scope。即static用于global variable时的含义。)
static Is also used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static
, so that the user won't be able to access them. This is encapsulation, a good practice.
(另一种跟static相关的scope -- file scope。即static用于global function时的含义。)
(static用于local variables of functions时的含义。)
(C++中引入static另外2种用途 -- static member variables & static member classes)
By making the member variables static, only one copy exists for all objects, rather than a copy for each object instantiated.
(static用于class member variables时的含义。)
Static data members are not part of objects of a given class type; they are separate objects. Consequently, it is better to think of static members as belonging to the class itself, not the objects of the class.
As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. These static members have external linkage. The following example illustrates this:
//-------------------------------------------------------------------------------------------------//
class BufferedOutput
{
public:
// Return number of bytes written by any object of this class.
short BytesWritten()
{
return bytecount;
}
// Reset the counter.
static void ResetCount()
{
bytecount = 0;
}
// Static member declaration.
static long bytecount;
};
// Define bytecount in file scope.
long BufferedOutput::bytecount;
int main()
{
}
//-------------------------------------------------------------------------------------------------//