Summary record of the use of static static member variables in C++

The road is hindered and long, and the line is coming. Keep your head down and work hard, if you don't talk, you will be a blockbuster! Come on, Sao Nian!

Reference

"C++ Primer Fifth Edition" page 268, section 7.6: Static members of classes .

"C++ Primer Fifth Edition" page 250, section 7.3.3: Class types .

Start of text

Why do you need static members of a class?

Sometimes a class requires some members to be directly related to the class itself, rather than to maintain associations with the various objects of the class.

For example: a bank account class may need a data member to represent the current benchmark interest rate.

In this case, we hope the interest rate directly associated with the class , and each object is not associated with the class.

It can be viewed from the following two angles:

  • From the perspective of implementation efficiency, it is not necessary for each object to store interest rate information;
  • More importantly, once interest rates fluctuate, we want all objects to use the new value.

How to declare static members?

In a statement before the members, add the keyword staticto associate it with the class together.

Need to pay attention to the following aspects:

  • Static members can be publicor private.

  • The types of static data members can be constants, references, pointers, class types, etc.

  • The static members of the class exist outside any object, and the object does not contain any data related to the static data members.

For example:

  • In the dog category, each dog has 4 legs, then my member can be associated with this category;
  • All objects created by this can use this member (each dog created by this has 4 legs);
  • There is no need to create a member for every dog ​​that uses this class and tell it that you have 4 legs.
  • Static member function is not bound to any object together, they do not contain thispointers.

  • As a result, it can not be declared as static member function const, but we also can not staticuse the body of the function thispointer.

This restriction applies to both the thisexplicit use is also effective to use an implicit call non-static members.

How to use static members of a class?

Use the scope operator "::" to directly access static members.

a::b();

Although a static member does not belong to an object of the class, we can still use the object, reference or pointer of the class to access the static member .

Member functions can directly use static members without going through scope operators.

How to define static members?

You can define static member functions both inside and outside the class .

When the external static member is defined in the class, can not be repeated statickeyword that declaration within a class of only appear.

note:

  1. Like all members of a class, when we point to a static member outside the class, we must specify the name of the class to which the member belongs.

  2. static The keyword only appears in the declaration statement inside the class.

Because static data members do not belong to any object of the class, they are not defined when the object of the class is created. This means that they are not initialized by the constructor of the class.

Generally speaking, we cannot initialize static members inside the class, we must define and initialize each static member outside the class. Like other objects, a static data member can only be defined once.

Similar to global variables, static data members are defined outside of any function. So once it is defined, it will always exist in the entire life cycle of the program.

The way to define static data members is similar to defining member functions outside of the class. We need to specify the type name of the object, then the class name, scope operator, and the name of the member itself.

double Account::interestRate = initRate();

This statement defines a named interestRateobject, that object is a class Accountstatic member of its type double.

Starting from the class name, the rest of the definition statement is within the scope of the class. Therefore, we can directly use the initRate()function.

note:

  1. Although initRateprivate, we can also use it to initialize interestRate.

  2. Like the definition of other members, interestRatethe definition can also access the private members of the class.

To ensure that the object is only defined once, the best way is to put the definition of the static data member and the definition of other non-inline functions in the same file.

In-class initialization of static members

Normally, static members of a class should not be initialized inside the class. However, it can provide a static member constwithin the class of the initial value of the integer type, but requires a static member must be a literal constant type constexpr.

The initial value must be a constant expression, because these members themselves are constant expressions, so they can be used in all places suitable for constant expressions.

class Account
{
    
    
    public:
        static double rate() {
    
    return interestRate;}
        static void rate(double);
        
    private:
        static constexpr int period = 30;     // period 是常量表达式
        double daily_tbl[period];
};

Even if a constant static data member is initialized inside the class, usually the member should be defined outside the class.

Static members can be used in certain scenarios, while ordinary members cannot

  • Static members are independent of any objects.

  • In some situations where non-static data members may be illegal, static members can be used normally.

  • Static data members can be incomplete types (a brief introduction in the extended information).

In particular, the type of a static data member can be the type of the class it belongs to. Non-static data members are restricted and can only be declared as pointers or references to the class they belong to.

class Bar
{
    
    
    public:
        // ...
    private:
        static Bar mem1;     // 正确:静态成员可以是不完全类型
        Bar *mem2;           // 正确:指针成员可以是不完全类型
        Bar mem3;            // 错误:数据成员必须是完全类型
};

Another difference between static members and ordinary members is that we can use static members as default arguments.

class Screen
{
    
    
    public:
        // bkground 表示一个在类中稍后定义的静态成员
        Screen& clear(char = bkground);
    private:
        static const char bkground;
};

A non-static data member cannot be used as a default argument, because its value itself is part of the object. The result of this is that an object cannot be provided to obtain the value of the member from it, which will eventually cause an error!

Extended information

Incomplete type

The declaration of analog functions can be separated from the definition, or we can just declare the class without defining it temporarily, as shown below:

class Screen;     // Screen 类的声明

This statement is sometimes called a forward declaration , it is introduced into the name of the program Screenand indicates Screena class type.

For type Screen, the statement before it is defined after a incomplete type , that is to say, at this time we know Screenis a class type, but in the end it is not clear which members included.

Incomplete types can only be used in very limited situations: you can define pointers or references to this type, or you can declare (but not define) functions that take incomplete types as parameters or return types.

If the content of the article is wrong, please comment / private message a lot of advice, thank you! If you think the content of the article is not bad, remember to click three links (like, bookmark, leave a message), your support is my greatest encouragement, thank you!

Guess you like

Origin blog.csdn.net/Fighting_Boom/article/details/108502836