Once a const object is created, its value cannot be changed, so the const object must be initialized . Compared to non-const types, the main difference is that the Const type object executes but does not change its operation content.
By default, const is only valid within a file. By default, the const-defined object is limited to the file class, and when a const with the same name appears in multiple files, it is equivalent to having separate variables defined separately in different files. So we only define the const object in one file, and in other files we just declare it. The extern keyword is added to the const object, whether it is a declaration or a definition, so it needs to be defined only once . As follows:
Define I in the File1.h file
extern const int i=3; Define I as a constant 3
When you refer to I in file2.h, just declare it and avoid redefining it.
extern const int i;
int a=i; So you can use I.
A const reference is referred to as a reference to a constant (reference to const), the reference type must be consistent with the object it refers to, but there are two exceptions, with the first exception being to allow arbitrary expressions to be used as initial values when initializing a constant reference . Allows the binding of a const object, a literal value, or even an expression, for a constant reference:
int i=42;
const INT &r1=i; Correct, at this time R1 and I bind
const INT &r2=42; Correct, bind a literal at this time 42
const INT &r3=r1*2; Correct, R3 is a constant reference, bound literal 84
int &r4=42; Error, non-binding literal value of very much reference
Limitations of const