c ++ const use in classification
Constant variable: const type specifier variable name
Often reference: const type specifier reference name &
Often the object: class name const object name
Chang member function: class name :: fun (parameter) const
Of constants: type specifier array name const [Size]
Often pointer: const * pointer type descriptor name, type name pointer * const specifier
In the constant variable ( const type specifier variable name), often quoted ( const type specifier & reference name ), often the object ( class name const object name), an array of constants ( type specifier const array name [size]), const " (type specifier is actually the class name is a custom) and "type specifier" or "class name" position as interchangeable:
const int a = 5; and int const a = 5; equivalents
The object name and class name const const object name class name equivalents
Usage 1: Constant
replaces the macro definitions in C, must be initialized (c ++ class that is not the case!) Declaration. const limits on how a constant, constant and does not describe how to allocate. If the compiler knows all use a const, and it can not even allocate space for const. The simplest case is the common values of the constants known at compile time, and do not need to allocate storage.
Usage 2: Pointer and constants
char * const cp; // pointer to a char const
char const * pc1; // pointer to const char
const char * pc2; // pointer const char (the latter two statements are equivalent)
from right to left to read memory manner:
. CP iS a const char pointer to point to another so that the string can not pc, but which can modify the contents of the string pointed
pc2 is a pointer to const char * pc2 so that the contents can not be changed, but pc2. you can point to other strings
And Note: non-const allows address assigned to a const object pointer to an object, does not allow the address of a const object assigned to a common, non-const pointer object.
Usage 3: const modified function arguments passed
to the function passed parameter is declared as const, indicating the use of this parameter is only for efficiency reasons, not want to call the function can modify the value of the object. Similarly, the parameter is declared as a pointer const, the object will not be modified by a function of the parameters referred to.
Usually qualify pointer parameters and reference parameters:
void Fun (const A * in); // modified pointer type arguments passed
void Fun (const A & in) ; // modified reference type parameter passed