[C++ Primer Chapter 7] Static members of classes

Sometimes a class needs some of its members to be directly related to the class itself, rather than to the various objects of the class.

declare static members

We associate a member with a class by adding the keyword static before its declaration. Like other members, static members can be made public or private. The types of static data members can be constants, references, pointers, class types, etc.

As an example, let's define a class that represents a bank's account records:

 1 class Account{
 2 
 3 public:
 4     void calculate() {amount+=amount*interestRate;}
 5     static double rate() {return interestRate;}
 6     static void rate(double);
 7 private:
 8     std::string owner;
 9     double amount;
10     static double interestRate;
11     static double initRate();
12 };

The static members of a class exist outside of any object, and the object does not contain any data related to static data members. Therefore, each Account object will contain two data members: owner and amount. There is only one interestRate object and it is shared by all Account objects.

Similarly, static member functions are not bound to any object, they do not contain this pointer . As a result, static member functions cannot be declared const, and we cannot use the this pointer within the body of a static function , a restriction that applies both to the explicit use of this and to the implicit use of calling non-static members.

Using static members of a class

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326276495&siteId=291194637