more and more annoying C + +, a simple const member variable is so troublesome. Concepts: const member variables, const member functions, const class variables
- A const member variable cannot be changed after it is initialized. Are consistent throughout the process. An assignment operation is not allowed.
- The const member function is a member function that guarantees that member variables are not modified.
- The const class variable refers to the use of a const when declaring a class variable, such as a const A;
Meaning:the const member variable guarantees that the value of a variable is never changed. the const member function guarantees that the state of the class will never be changed. (The value of the variable will never be modified)
Rules:
Rule one:
Const member variables can only be initialized in the constructor's initialization list and cannot be assigned in the constructor body. Otherwise, write errors are generated for read-only data.
Rule two:
Const member variables cannot have any assignment operations.
Rule three:
Non-const member functions and const member functions can read access to const or non-const member variables of non-const class variables.
Rule four:
Non-const member functions do not have access to any member variable of the Const class variable. Only the const member function can.
Rule five:
Any assignment to a member variable is not allowed in the Const member function. (Ensure that the member variable values are not modified)
Rule VI:
The const member function cannot call a non-const member function. (or to ensure that member variable values are not modified, God knows what non-const member functions you call will do)
values: (These can help you understand the memory)
Const variable: I am eternal, any assignment is an insult to me. (rule one or two)
Const member function: The so-called Melon is not satisfied with the title, Lee under the crown, I know suspicion (rule five); and I am the only one to believe that those who do not have a const certification are good and bad, I can not trust them. I know there may be good people among them, but we have to get rid of the risks, right? (Rule VI)
Const CLASS Variable: I was born with the noble mark of a const, I can only do noble deeds. (Rule IV)
Principle of implementation: to Be Continued ...
C++const member Rules