Home > Article > Backend Development > Can the constructor of a class in C++ initialize static member variables?
The constructor of a class in C can initialize static member variables. The initialization syntax is as follows: use staticMemberVariable = ...; declaration in the constructor. Static member variables are initialized only once when the constructor is executed for the first time. Static member variables can only be initialized in the constructor, and the reference type must be initialized to nullptr or a valid reference. Static member variables cannot be declared const.
The constructor of a class in C can initialize static member variables
Yes, the constructor of a class in C Static member variables can be initialized.
Syntax for initializing static member variables
To use the constructor to initialize static member variables, you can use the following syntax:
<code class="cpp">class ClassName { public: ClassName() { // 初始化静态成员变量 staticMemberVariable = ...; } static int staticMemberVariable; };</code>
Initialization time
When a class object is created, static member variables will only be initialized once, that is, when any constructor of the class is executed for the first time.
Note
nullptr
or a valid reference in the constructor. const
because their values need to be modified in the constructor. The above is the detailed content of Can the constructor of a class in C++ initialize static member variables?. For more information, please follow other related articles on the PHP Chinese website!