How to use static members of the class? How to access between ordinary member variables?

1. Record the reason

I have been confused about how to access between ordinary members and static members. I often forget that when I recently learned the singleton mode of design patterns, I also reviewed the static keyword in "C++ Primer" by the way. I have some new understandings, which may not be completely correct. , If there is an error, I hope the readers will raise it

 

2. Introduction on "C++ primer"

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

For example, define a class and use it to represent the standard of bank account ( note the use of several static, when to use static ):

class Bank
{
public:
    static Account *GetInstance()
    {
        if(acc == nullptr)//单线程安全版的单例
        {
            acc = new Bank();//调用自定义的构造函数
        }
        return acc;
    }
    static double GetRate()
    {
        return interestRate;
    }
    void clear()
    {
        //释放工作
    }
private:
    Bank(){}//构造函数私有化
    Bank(const Bank&){}//拷贝构造函数私有化

    static double interestRate;//基准汇率,该银行所有账户共有一个汇率
    static Bank* acc;//一个实例
};

double Bank::interestRate = 3.8;

Bank Bank::acc = nullptr;

We declare the bank exchange rate as static here, because all accounts use the same set of exchange rates; saving space is one aspect. Moreover, if the exchange rate needs to be adjusted due to national regulations or business needs, just adjust the value of the Bank’s interestRate. .

The instance acc here can be set to be shared according to requirements. If it is private, it can only be obtained by calling GetInstance() ; if it is shared, it can be obtained directly by using Account::acc where needed

 

(Some points to be noted in the singleton mode will be discussed in the next section)

Description:

(1) The static members of the class exist outside the class object, and all objects can be shared ( if static is a private member, it can only be accessed through the class object; if it is shared, it can be directly accessed through the class name and scope, such as Bank:: acc ), the object does not include any data related to static data members.

(2) Static members and functions are not bound to any object, it does not contain the this pointer, so static members cannot directly access ordinary members of the class (good understanding, because ordinary members of the class default this pointer, that is to say, the function in the class is used Ordinary members, such as interestRate, the complete should be this->interestRate)

(3) The static member function does not contain the this pointer. As a result, the static member function cannot be declared as const , and the this pointer cannot be used in the body of the static function. This restriction applies to both the explicit use of this and the implicit use of calling non-static members.

(4) Although static members do not belong to an object, we can use class objects, references or pointers to access static members (here designed as a singleton, no object can be created, otherwise you can use: Bank b; b.GetRate( );)

(5) Because the static member does not belong to an object, it is impossible to initialize the static member with the constructor , but its value can be changed in the constructor

(Member initialization mentions that if the class member is a constant or a reference type, it can only be initialized through the delegate constructor of the class:

class A

{

A(string str) {//...}

A(int i,string str): A(str) {}//Delegate the previous constructor to create

};

(6) Interspersed with a small knowledge point, some people may wonder whether the member variable acc can be of type Bank instead of a pointer. No way! The reason is that Bank members must all be complete types. Let's put it this way, a class needs to know its own size when it is created. Non-static members of a class occupy the class space. If the Bank contains itself as a member, for example, it has 4 bytes for int type members and 4 bytes for pointers. , And its own members. Next, how much space does it take up? Well, it contains 4 bytes of an int type, 4 bytes of pointer, and itself. . . I found that I didn't. I was in an endless loop, and I couldn't determine my size.

 

3. Points to note in singleton mode

(1) The constructor and copy constructor must be written by yourself, and written as private members, the purpose is to prevent external definition of multiple objects, because the default constructor generated by the compiler is shared.

(2) The instance acc is a singleton and is shared by all banks, so you need to use the static statement

(3) As a singleton mode, it is not possible to create objects, so it is necessary to declare the interface GetInstance() to obtain the singleton as static, so that you can use Bank::GetInstance() to get

(4) As one of the design pattern principles, single responsibility (a class has only one direction that causes it to change), the singleton pattern here is best to only create work, not to integrate too many interfaces

 

4. What scenarios use static members

When the member is shared by all class objects, using static first can save memory overhead, and second, when the member value needs to be changed, all objects can be automatically changed to the new value.

 

5. Summary

The simple summary of the access mechanism between static and non-static is one point: non-static members of a class can access static members of its own class, while static members of a class do not occupy the space of the class (equivalent to just providing an access right to the class ), so it does not contain this pointer and cannot access non-static members.

 

 

Guess you like

Origin blog.csdn.net/qq_38915078/article/details/112667316