[C++] Application of static member variables, static member functions and static const in classes

Foreword:

        In C++, static member variables, static member functions, and static constants are very useful features, which can easily organize data and operations, and improve code efficiency and readability. This article will introduce the characteristics, application, singleton mode and factory mode of static member variables, static member functions and static constants.

1. Static members in C++

        In a class definition, its members (including member variables and member functions), which can be declared as static with the keyword static, are called static members. No matter how many objects of this class are created, there is only one copy of static members, and this copy is shared by all objects belonging to this class.

1. Static member variables

        Static member variables are member variables of a class that do not belong to any object and are not included in the object allocation space of the class. There is only one copy of static member variables, which can be shared among multiple objects, and are usually used to represent data of a global nature, such as counters, identifiers, etc.

        The definition of static member variables is similar to the definition of ordinary member variables, but the static keyword needs to be added in front of the variable name. In the definition of static member variables, there is no need to add the static keyword, but there must be a type and a name.

The following is an example definition of a static member variable:

class MyClass {
public:
    static int m_staticVar;
};

int MyClass::m_staticVar = 0;

        In the above code, we define a class named MyClass, which contains a public static member variable m_staticVar. Outside the class, we need to define and initialize it.

        Static member variables can be referenced by class name or object name . For static member variables referenced by class names, scope operators need to be added, such as MyClass::m_staticVar. For static member variables referenced by object names, scope operators also need to be added, such as myObject.m_staticVar.

int main() {
  // 通过类名来访问静态成员变量
  MyClass::m_staticVar = 10;

  // 创建对象来访问静态成员变量
  MyClass myObject;
  myObject.m_staticVar = 20;

  // 输出静态成员变量的值
  cout << MyClass::m_staticVar << endl; // 20
  cout << myObject.m_staticVar << endl; // 20

  return 0;
}

2. Static constants

Static constants refer to constants that will not change         during the running of the program (the value cannot be changed) and can be used in the global scope. In C++, we can use static member variables to define static constants. Static constants have nothing to do with the instantiation of the class. There is only one copy, which can be shared among multiple objects, such as defining mathematical constants, file paths, etc.

        Since static constants are similar to static variables (only the value is fixed), in order to distinguish them from static variables, it is best to initialize them inside the class.

The following is a sample code that uses static member variables to define static constants:

class MyClass {
public:
    static const float PI= 3.1415926;
};

        In the above code, we defined a class named MyClass, which contains a public static member constant PI. Inside the class, we initialize it to 3.1415926.

        Static constants can be referenced by class name or object name. For static constants referenced by class names, scope operators need to be added, such as MyClass::PI. For static constants referenced by object names, scope operators also need to be added, such as myObject.PI. (Since there is no difference between using and static variables, no demonstration will be made here)

3. Static member functions

        Static member functions are member functions of a class, they do not belong to any object, and can be called directly through the class name. Static member functions are usually used to perform operations of a global nature, such as factory functions, singleton patterns, etc.

        The definition of a static member function is similar to the definition of a normal member function, but the static keyword needs to be added before the function name. Static member functions can only access static variables , not ordinary member variables. The use of static member functions is the same as static member variables. Static member functions also have access rights. Ordinary member functions can access static member variables and non-recurring member variables .

The following is an example definition of a static member function:

#include <iostream>
using namespace std;

class MyClass {
public:
  // 普通成员函数可以访问 static 和 non-static 成员属性
  void changeParam1(int param) {
    mParam = param;
    sNum = param;
  }
  // 静态成员变量和函数只能访问 static 成员属性
  static int sNum;
  static void changeParam2(int param) {
    sNum = param;
  }
private:
  int mParam;
};

// 定义静态成员变量
int MyClass::sNum = 0;

int main() {
  // 通过类名来访问静态成员变量和函数
  MyClass::sNum = 10; // 修改静态成员变量
  MyClass::changeParam2(20); // 调用静态成员函数
  cout << MyClass::sNum << endl; // 20

  // 创建对象来访问非静态成员
  MyClass obj;
  obj.changeParam1(30); // 修改非静态成员变量
  cout << obj.sNum << endl; // 20
  return 0;
}

        In the above code, we define a class named MyClass, which contains a non-static member variable mParam and two static member functions changeParam2 and changeParam3.

        In the public area, we define a static member variable sNum and initialize it outside the class. We also implemented a common member function changeParam1 called through the object, in which the values ​​of non-static and static member variables are modified.

        In the main function, we use the class name to access static member variables and static member functions, and demonstrate how to use objects to access non-static member variables and non-static member functions.

2. Combining software design patterns

        Software design patterns are a way of sharing experiences on how to solve common problems in software design. It refers to some recurring problems that are often encountered in object-oriented software design, and the solutions to these problems. These solutions are proven and widely recognized as a best practice approach in software design.

        The main purpose of software design patterns is to improve code reusability, maintainability and scalability. By using design patterns, developers can divide the code into a series of single-responsibility classes, allowing each class to focus on completing its own tasks, thereby improving the readability and maintainability of the code. In addition, design patterns can also reduce the complexity of the system, improve the flexibility and adaptability of the code, and facilitate the response to system changes.

        In addition, design patterns can also promote the standardization and normalization of the system. Since the design pattern is a proven best practice method, it can be widely applied to various projects to promote communication between developers and improve development efficiency and code quality.

        All in all, software design patterns are a set of reusable solutions defined to solve complex problems. By using these solutions, the maintainability, scalability and readability of software systems can be improved, and code errors and duplication can be reduced. .

The following is a brief list of some common software design patterns: (for reference only)

  1. Factory Pattern (Factory Pattern): Return a new object of a specific class on demand without knowing the specific implementation details of the class.

  2. Singleton Pattern: Ensures that a class has only one object and provides global access to that object.

  3. Observer Pattern: Define a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on the object will be notified and automatically updated.

  4. Adapter Pattern: Converts two incompatible interfaces into compatible interfaces.

  5. Strategy Pattern (Strategy Pattern): Define a family of algorithms, encapsulate each algorithm, and make them interchangeable, so that the algorithm can change independently of the client using it at runtime.

  6. Chain of Responsibility Pattern: Decouples the sender and receiver of a request and gives multiple objects a chance to handle the request.

  7. Template Method Pattern: Defines the framework of an algorithm and allows subclasses to provide concrete implementations for one or more steps.

  8. Facade Pattern: Provides a simple interface that hides the complexity of the system, making it easier for clients to use the system.

  9. Decorator Pattern: Dynamically attach responsibilities to objects, extending the functionality of an object without affecting its interface.

  10. Builder Pattern: Separate the construction process of a complex object from its representation, so that the same construction process can create different representations.

The above is just for understanding. This article mainly combines the demonstration of static members in singleton mode and factory mode.

1. Singleton mode

        The singleton pattern is a commonly used software design pattern. In its core structure contains only one special class called singleton . The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, so as to facilitate the control of the number of instances and save system resources.

        In singleton mode, we usually use static member variables to store the only instance, and use static member functions to get this instance. This avoids creating multiple identical object instances in the system, saves system resources, and facilitates global access to instances.

The following is a sample code that uses static member variables to implement the singleton pattern:

class Singleton {
private:
    static Singleton* m_instance;
    Singleton() {}
public:
    static Singleton* getInstance() {
        if (m_instance == nullptr) {
            m_instance = new Singleton();
        }
        return m_instance;
    }
};

Singleton* Singleton::m_instance = nullptr;

        In the above code, we define a class named Singleton, which contains a private static member variable m_instance and a public static member function getInstance. In the getInstance function, we check if m_instance is empty, if it is empty we create the instance, otherwise we return the existing instance.

2. Factory mode

        The factory pattern is a commonly used software design pattern. It contains a factory class in its core structure , which provides a method for creating objects to decouple the creation and use of objects .

        In the factory pattern, we usually use static member functions to create and return object instances. This can decouple the creation and use of object instances, reduce the complexity of the system, and improve the maintainability and scalability of the code.

The following is a sample code that implements the factory pattern using static member functions:

class Product {
public:
    virtual ~Product() {}
};

class ProductA : public Product {
public:
    ProductA() {}
};

class ProductB : public Product {
public:
    ProductB() {}
};

class Factory {
public:
    static Product* createProductA() {
        return new ProductA();
    }
    static Product* createProductB() {
        return new ProductB();
    }
};

        In the above code, we define an abstract base class Product and two concrete classes ProductA and ProductB inherited from Product. In the Factory class, we define two static member functions createProductA and createProductB, which are used to create and return object instances of ProductA and ProductB.

Summarize

        This article introduces the characteristics, applications, common software design patterns and implementation of singleton and factory patterns of static member variables, static constants and static member functions in C++. Static member variables, static constants, and static member functions can help us better organize data and operations, and improve code efficiency and readability.

        Singleton mode and factory mode are commonly used software design patterns, which can decouple the creation and use of objects, reduce the complexity of the system, and improve the maintainability and scalability of the code.

        Through the study of this article, we can better apply static member variables, static constants and static member functions in C++, and understand common software design patterns and how to implement singleton patterns and factory patterns.

Guess you like

Origin blog.csdn.net/crr411422/article/details/131001839