Constants defined with const have their space released after exceeding their scope, while static constants defined with static do not release their storage space after the function is executed.

static means static. A class's static member functions and static member variables are associated with the class, not with specific objects of the class. Even without a specific object, the class's static member functions and member variables can be called. Generally, a class's static function is almost a global function, except that its scope is limited to the file containing it.

In C++, static member variables cannot be initialized inside the class. Inside the class is only a declaration; the definition must be outside the class definition body, usually initialized in the class's implementation file, such as:double Account::Rate = 2.25;

The static keyword can only be used in the declaration inside the class definition body; it cannot be marked as static when defining.

In C++, const member variables also cannot be initialized at the class definition; they can only be initialized through the constructor initializer list, and a constructor must exist.

A const data member is constant only during the lifetime of a particular object, but it is variable for the entire class. Because a class can create multiple objects, different objects can have different values for their const data members. Therefore, const data members cannot be initialized in the class declaration, because when an object of the class has not been created, the compiler does not know what the value of the const data member is.

Initialization of const data members can only be done in the initializer list of the class's constructor. To establish a constant that is constant throughout the entire class, you should use an enum constant in the class, or static const.

class Test{ public: Test():a(0){} enum {size1=100,size2=200}; private: const int a;//Can only be initialized in the constructor initializer list static int b;//Define and initialize in the class's implementation file conststatic int c;//Same as static const int c; }; int Test::b=0;//static member variables cannot be initialized in the constructor initializer list because they do not belong to a specific object. cosnt intTest::c=0;//Note: When assigning a value to a static member variable, the static modifier is not needed, but const must be added.

The main purpose of const member functions is to prevent member functions from modifying the contents of the object. That is, a const member function cannot modify the values of member variables, but it can access member variables. When a member function is called on a const object, that function can only be a const member function.

The main purpose of static member functions is to serve as global functions within the class scope. They cannot access non-static data members of the class. A class's static member functions do not have a this pointer, which leads to:

  • 1. Cannot directly access the class's non-static member variables or call non-static member functions.
  • 2. Cannot be declared as virtual.

On the initialization of static, const, static const, and const static members

1. Initialization of const members in a class:

When creating a const in a class, you cannot give it an initial value.

class foo{ public: foo():i(100){} private: const int i=100;//error!!! }; //Or initialize it in this way foo::foo():i(100){}

2. Initialization of static members in a class:

Static variables in a class belong to the class, not to a specific object. They have only one copy during the entire execution of the program. Therefore, they cannot be initialized when defining an object; that is, they cannot be initialized with a constructor. The correct initialization method is:

data type class name::static data member name = value;
class foo{ public: foo(); private: staticint i; }; intfoo::i=20;

This indicates:

  • 1. Initialization is performed outside the class body, and static is not added in front, to avoid confusion with ordinary static variables or objects.
  • 2. When initializing, do not add the member's access control specifiers such as private, public, etc.
3. When initializing, use the scope resolution operator to indicate the class it belongs to. Therefore, static data members are members of the class, not members of an object.

3. Initialization of static const and const static members in a class

These two ways of writing have the same effect. For ease of memory, only one general initialization method is explained here:

class Test{ public: static const int mask1; conststatic int mask2; }; constTest::mask1=0xffff; constTest::mask2=0xffff; //Their initialization is no different, although one is a static constant and the other is a constant static. Static ones are stored in the global variable area; in fact, the final result is the same. Different compilers may handle them differently, but the final result is the same.

Complete example

Example

#ifdef A_H_ #define A_H_ #include <iostream> usingnamespace std; class A{ public: A(int a); staticvoid print();//Static member function private: static int aa;//Declaration of static data member staticconst int count;//Constant static data member (can be initialized in the constructor) const int bb;//Constant data member }; int A::aa=0;//Definition + initialization of static member const int A::count=25;//Definition + initialization of static const member A::A(int a):bb(a){//Initialization of constant member aa+=1; } void A::print(){ cout<<"count="<<count<<endl; cout<<"aa="<<aa<<endl; } #endif void main(){ A a(10); A::print();//Access static member function through the class a.print();//Access static member function through an object }

Initialization location

Static members cannot be initialized in the class definition (except for int). They cannot be initialized in the header file.

For example, if myclass.h is defined, it is generally initialized in myclass.cpp.


Static members of C++ classes (static)

Static members are proposed to solve the problem of data sharing. There are many ways to achieve sharing, such as setting global variables or objects as one method. However, global variables or objects have limitations. In this chapter, we mainly discuss using static members of a class to achieve data sharing.

Static data member

In a class, static members can achieve data sharing among multiple objects, and using static data members does not break the principle of hiding, thus ensuring safety. Therefore, static members are members shared by all objects of the class, not members of a particular object.

Using static data members can save memory because they are common to all objects. Therefore, for multiple objects, static data members are stored in only one place and shared by all objects. The value of a static data member is the same for every object, but its value can be updated. As long as the value of the static data member is updated once, all objects are guaranteed to access the same updated value, which improves time efficiency.

The usage and precautions for static data members are as follows:

1. When defining or declaring a static data member, add the keyword static in front.

2. Initialization of static members is different from initialization of ordinary data members. The format for initializing static data members is as follows:

 
<data type><class name>::<static data member name>=<value>

This indicates:

  • (1) Initialization is performed outside the class body, and static is not added in front, to avoid confusion with ordinary static variables or objects.
  • (2) When initializing, do not add the member's access control specifiers such as private, public, etc.
  • (3) When initializing, use the scope resolution operator to indicate the class it belongs to. Therefore, static data members are members of the class, not members of an object.

3. Static data members are stored statically; they have static lifetime and must be initialized.

4. When referencing a static data member, use the following format:

<class name>::<static member name>

If the access permission of the static data member permits (i.e., it is a public member), the static data member can be referenced in the program using the above format.

The following is an example to illustrate the application of static data members:

Example

#include … class Myclass{ public: Myclass(int a, int b, int c); void GetNumber(); void GetSum(); private: int A, B, C; static int Sum; }; int Myclass::Sum = 0; Myclass::Myclass(int a, int b, int c){ A = a; B = b; C = c; Sum += A+B+C; } void Myclass::GetNumber(){ cout<<"Number="<<a<<","<<b<<","<<c<<endl; } void Myclass::GetSum(){ cout<<"Sum="<<sum<<endl; } void main(){ Myclass M(3, 7, 10),N(14, 9, 11); M.GetNumber(); N.GetNumber(); M.GetSum(); N.GetSum(); }

From the output, it can be seen that the value of Sum is equal for both object M and object N. This is because when initializing object M, the values of the three int data members of object M are summed and assigned to Sum, so Sum stores that value. When initializing object N, the values of the three int data members of object N are summed and then added to the existing value of Sum, so Sum will store the new value. Therefore, the value referenced through either object M or object N is the same, namely 54.

Static member function

Like static data members, static member functions belong to the static members of the class; they are not object members. Therefore, referencing static members does not require using an object name.

In the implementation of a static member function, non-static members declared in the class cannot be referenced directly, but static members declared in the class can be referenced. If a static member function needs to reference non-static members, it can do so through an object. The following example illustrates this.

Example

#include … class M{ public: M(int a){ A=a; B+=a; } static void f1(M m); private: int A; static int B; }; void M::f1(M m) { cout<<"A="<<m.a<<endl; cout<<"B="<<b<<endl; } int M::B=0; void main() { M P(5),Q(10); M::f1(P); //No object name is needed when calling M::f1(Q); }

Readers can analyze the result by themselves. It can be seen that calling a static member function uses the following format:

  
<class name>::<static member function name>(<parameter list>);

Initialization methods for various types of member variables in C++

Different types of members in C++ have different initialization methods depending on whether they are static or const. Java's syntax is not this complicated; no wonder so many people all go to learn Java. In the past, I was asked this question in an interview and could not answer it. When writing code, I often messed it up. Here I looked through a book and summarized it.

//-----------------Test.h---------------------------- #pragma once class Test { private : int var1; // int var11= 4; incorrect initialization method const int var2 ; // const int var22 =22222; incorrect initialization method static int var3; // static int var3333=33333; error: only static const int members can be initialized by direct assignment static const int var4=4444; // Correct, static const members can be initialized directly static const int var44; public: Test(void); ~Test(void); }; //--------------------Test.cpp----------------------------------- #include ".\test.h" int Test::var3 = 3333333; // Correct initialization method for static members // int Test::var1 = 11111;; error: only static members can be initialized // int Test::var2 = 22222; error // int Test::var44 = 44444; // incorrect method, gives redefinition error Test::Test(void):var1(11111),var2(22222)Correct initialization method//var3(33333) cannot be initialized here { var1 =11111; // Correct, ordinary variables can also be initialized here //var2 = 222222; error, because a constant cannot be assigned; it can only be initialized in the "constructor initializer (constructor initialization list)" var3 =44444; // This assignment is correct, but since all objects share one static member, it will affect others; this can hardly be called initialization } Test::~Test(void){} //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Some member variables have special data types, and their initialization methods also differ from member variables of ordinary data types. These special types of member variables include:

  • a. Constant member variables
  • b. Reference member variables
  • c. Static member variables
  • d. Integral static constant member variables
  • e. Non-integral static constant member variables

For constant member variables and reference member variables, initialization must be done through the constructor initialization list. Assigning values to constant member variables and reference member variables within the constructor body is not feasible.

Initialization of static member variables is also rather special.

Refer to the following code and its comments:

// Initialization of Special Data Member #include <iostream> using namespace std; class BClass { public: BClass() : i(1),ci(2), ri(i) // For constant member variables and reference member variables, initialization must be done through the parameterized list. Assigning values within the constructor body is not feasible. { // Ordinary member variable } voidprint_values() { cout<< "i =\t" << i << endl; cout<< "ci =\t" << ci << endl; cout<< "ri =\t" << ri << endl; cout<< "si =\t" << si << endl; cout<< "csi =\t" << csi << endl; cout<< "csi2 =\t" << csi2 << endl; cout<< "csd =\t" << csd << endl; } private: inti; // Constant member variable constint ci; // Reference member variable int&ri; // Static member variable staticint si; //staticint si2 = 100; // error: only static constant member variables can be initialized this way // Static constant member variable staticconst int csi; // Initialization of static constant member variable (Integral type) (1) staticconst int csi2 = 100; // Static constant member variable (non-Integral type) staticconst double csd; //staticconst double csd2 = 99.9; // error: only static constant integral data members can be initialized within the class // Initialization of static member variable (Integral type) }; // Initialization of static constant member variable (Integral type) int BClass::si = 0; // Initialization of static constant member variable (non-Integral type) const int BClass::csi = 1; // When initializing csi2 in (1), according to Stanley B. Lippman, the following line is necessary. const double BClass::csd = 99.9; // However, in VC2003, having the following line will cause an error, while in VC2005, the following line is optional; this depends on the compiler. C++ static member summary, C++, static const int BClass::csi2; int main(void) { BClassb_class; b_class.print_values(); return0; }

C++ static member summary, C++, static

Afterwards, I reflected deeply and decided to thoroughly summarize the key points about static class members, so that in future interviews I won't be passive on such issues.

Static class members include two parts: static data members and static function members.

Static data members

Static data member

1. Definition of static data members.

Static data members are actually global variables in the class scope. Therefore, the definition (initialization) of static data members should not be placed in header files. (Declaration vs. definition (initialization)) Their definition method is the same as global variables. Example:

File

xxx.h// Declaration. Standard C++ supports initialization of integral types in the class body, but VC6 does not.class base{ private: static const int _i;File }; xxx.cpp// Definition (initialization) is not restricted by private and protected access limits.const int base::_i=10;Note:

Do not attempt to define (initialize) static data members in header files. In most cases, doing so will cause errors such as redefinition. Even if you addor#ifndef #define #endifit still won't work.#pragma once2. Static data members are shared by all objects of the class, including objects of derived classes of this class. That is, derived class objects and base class objects share the base class's static data members. Example:

// Declaration

class base{ public : static int _num;// Real definition of static data member }; int base::_num=0;// The result is 1,2; it can be seen that the derived class and the base class share one static data member. class derived:public base{ }; main() { base a; derived b; a._num++; cout<<"base class static data number_num is"<<a._num<<endl; b._num++; cout<<"derived class static datanumber _num is"<<b._num<<endl; } 3. Static data members can be used as default arguments of member functions, while ordinary data members cannot. Example:

// Correct, _staticVar is a static data member

class base{ public : static int _staticVar; int _var; void foo1(int i=_staticVar);// Error, _var is an ordinary data member void foo2(int i=_var);4. The type of a static data member can be the type of its own class, while an ordinary data member cannot. An ordinary data member can only be declared as a pointer or reference to the type of its own class. Example: };

// Correct, static data member

class base{ public : static base_object1;// Error base _object2;// Correct, pointer base *pObject;// Correct, reference base &mObject;5. I don't know whether this feature belongs to standard C++ or is a feature specific to VC6. };

The value of a static data member can be legally changed in a const member function. Example:

// const member function

class base{ public: base(){ _i=0; _val=0; } mutable int _i; static int _staticVal; int _val; void test() const{// Correct, mutable data member _i++;// Correct, static data member _staticVal++;// Error _val++;Static member functions } }; int base::_staticVal=0;

Static member function

1. The address of a static member function can be stored in an ordinary function pointer, while the address of an ordinary member function needs to be stored in a class member function pointer. Example:

// Ordinary function pointer

class base{ static int func1(); int func2(); }; int (*pf1)()=&base::func1;// Member function pointer int (base::*pf2)()=&base::func2;2. Static member functions cannot call non-static members of the class, because static member functions do not contain a this pointer.

3. Static member functions cannot be declared as virtual, const, or volatile functions at the same time. Example:

// Error

class base{ virtual static void func1();// Error static void func2() const;// Error static void func3() volatile;The last point to mention is that static members can be accessed independently, that is, they can be accessed without creating any object instance. };

Author: SDMrFeng

Original: https://blog.csdn.net/tobefxz/article/details/14109697

Pycharm Import Python packages, modules