If we want to share a single data within a range before we have a description of this chapter, we will set up global objects, but object-oriented programs are made up of objects, how can we share data within the scope of a class?
This issue is the focus of this chapter:
Class members or member functions declared as static can be shared within the scope of the class, and we refer to such members as static members and static member functions.
Here we use several examples to illustrate this problem, the members of the class need to be protected, and normally, in order not to violate the package characteristics of the class, we set the class member to protected (protection State), but to simplify the code, make the problem to be explained more intuitive, easier to understand, We are set to public here.
The following program we do a mock access example, in the program, each set up an object we set the class static member to automatically add one, the code is as follows:
#include <iostream>
using namespace std;
Class Internet
{
Public:
Internet (char *name,char *address)
{
strcpy (internet::name,name); br> strcpy (internet::address,address);
count++;
}
static void Internet::sc ()//statically member function
{
Cout<<count<<endl;
Internet &rq ();
Public:
Char name[20];
Char address[20];
Static int count;//here if you write a static int count=0; the wrong
};
internet& INTERNET::RQ ()//Returns a referenced member function
{
return *this;
}
int internet::count = 0;//static member initialization
Void Vist ()
{
Internet A1 ("China Software Development Lab", "www.cndev-lab.com");
Internet A2 ("China Software Development Laboratory", "www.cndev-lab.com");
}
void fn (Internet &s)
{
Cout<<s.rq (). Count;
}
Void Main ()
{
cout<<internet::count<<endl;//the output of the static member value
Vist ();
INTERNET::SC ()///static member function call
Internet B ("China Software Development Laboratory", "www.cndev-lab.com");
INTERNET::SC ();
FN (b);
Cin.get ();
}
The code above we used several common ways to create objects, when a new object is created and its constructor is invoked, the static member cout is run with 1 operations, and the initialization of the static member should precede the main function call and not appear in the declaration of the class, and through the observation of the running process we find that The state of the static member count is not redefined as a new object is created. As we understand that static members of a class belong to the class rather than to which object, the use of the static member should be the class name plus the field that distinguishes the alphanumeric member name, which in the preceding code is the Internet:: Count, although we can still use the object name dot action symbol plus member name, but not recommended, static State class members of the attribute is belong to the class and not belong to an object.