Const is a keyword in C that is protected against the effects of changes outside! You can modify variables, parameters, return values, and even function bodies. Const can improve the robustness of the program, you just need to use any place you want.
(i) const modifier parameters. Const can only modify input parameters.
1, if the input parameters are pointer-type, with the const modifier can prevent the pointer from being accidentally modified.
2. If the parameter is passed by value, no const is required because the function automatically generates a temporary variable to copy the parameter.
3, the parameters of non-internal data type, need temporary object copy parameters, and temporary object construction, destruction, replication is more time-consuming, it is recommended to use the pre-const reference method to pass non-internal data types. The internal data type does not need to be passed by reference.
(ii) The const modifier function return value.
1. The function returns a const pointer, indicating that the pointer cannot be altered, and only assigns the pointer to a const-modified pointer variable of the same type.
2, the function return value is the value pass, the function will assign the return value to the external temporary variable, with the const meaningless! Both internal and non-internal data types.
3, the function uses the reference way returns not many occasions, only appears in the class assignment function, the purpose is realizes the chain expression.
(c) const+ member functions. Any function that does not modify the data member should be declared as a const type, and if the const member function modifies the data member or calls other functions to modify the data member, the compiler will give an error!
Class Stack
{
Public
void push (int elem);
void pop (void);
int GetCount (void) const;
Private
int m_num;
int m_date[10];
};
int Stack::getcount (void) const
{
m_num++;
}
Compiler output error message: Error c2166:l-value specifies const object.
(d) A const modifier variable that indicates that the variable cannot be modified.
1. const char *P indicates that the pointing content cannot be changed
2, char * const P, is to declare p as a constant pointer, its address cannot be changed, is fixed, but its content can be changed.
3, this const pointer is the first two combinations, so that the point of the content and address can not be changed.
Const double PI = 3.14159;
Const double *const pi_ptr = π
C + + Const SUMMARY