}?
The sudden thought of static, const, static const, and their initialization
A const-defined constant exceeds its scope and is freed, and static constants that are defined in the function do not release their storage space after a straight line.
For each of the following initialization rules:
- Const-defined constants that need to be initialized in the initialization list.
- Static variables defined by static, which need to be initialized outside the class.
- const static, like the static const, is also required to be initialized outside the class.
- The const form of a method whose primary function is to prevent member functions from modifying the value of a member variable. A scope is an object, and different objects can have different values for const-defined constants.
- The method of static form has its main function in order to be used as a global method. The scope is the entire class. Typically used as a tool class, different objects can modify the values of static variables,
You cannot modify the value of a const static constant.
?
Note: In order to establish a constant value in a class, the Enum enumeration can be implemented in addition to the const static.
?
Examples are as follows:
BlankTest.cpp: Defines the entry point of the console application.
//
The difference and connection between const, static, const static, enum
#include "stdafx.h"
#include <iostream>
using namespace Std;
?
class MyClass
{
???? const int m;
Public:???? static int n;
???? const static int mn;
???? Enum
???? {
???????? Size1 = 50,//enum variable not in; Colon, only, comma.
???????? Size2 = 60
????};
Public://If not public, compile error. A friend class cannot access a private member.
???? static void print ();
???? const void Print2 ();
?
MyClass (int a);
};
?
int myclass::n = 10; Definition of static member + initialization
const int MYCLASS::MN = 20;
?
Myclass::myclass (int a): M (a)//use A to initialize a const member, where you can write a number directly, such as 10, is no problem.
{
???? n + = 1;//Description We can make changes to the static variable in the constructor
}
?
?
void MyClass::p rint ()
{
???? cout << "count=" << mn << Endl;
}
?
const void MyClass::p rint2 ()
{
???? m = 20; Error, error message: The expression must be a modifiable left-hand value.
???? cout << "Const =" << m << Endl;
???? cout << "static =" << n << Endl;
}
int _tmain (int argc, _tchar* argv[])
{
???? MyClass a (10);
???? A.print ();//accessing static member functions through objects
???? MyClass::p rint ();//access static member functions by class
?
???? A.print2 ();
???? A.N + = 1; The static variable can be changed. Static const variables cannot be changed.
???? A.print2 ();
?
???? cout << "enum =" << a.size1 << Endl;
???? A.mn + = 1;//error, static constants cannot modify the left value.
???? return 0;
}