Const for C ++ Programming

Source: Internet
Author: User

I. Basic statements
1. const int r = 100; // standard const variable declaration and initialization, because the default internal connection must be initialized, its scope is this file, after passing the type check, the compiler replaces it with 100 during compilation.
2. extend const int r = 100; // change const to an external connection to expand to the global level. memory will be allocated during compilation and can be initialized without being declared, the compiler considers it defined elsewhere in the program.
3. const int r [] = {1, 2, 3, 4 };
Struct S {int a, B ;};
Const S [] = {(1, 2), (3.4)}; // the above two types are constant sets, and the compiler allocates memory for them, therefore, you cannot use the value during compilation, for example, int temp [r [2]. Such a compiler reports that constant expressions cannot be found.

2. for pointers
1. const int * r = & x; // declare r as a pointer to x of a constant. The object pointed to by r cannot be modified, but it can point to a constant of any address.
2. int const * r = & x; // It is equivalent to usage 1 and has no difference.
3. int * const r = & x; // declare r as a constant pointer. the pointer pointing to x and r cannot be modified, but the content of the address pointed to can be modified.
4. const int * const r = & x; // in combination with 1 and 3 usage, r is a constant pointer pointing to a constant.

Iii. type check
You can assign a non-const object to a pointer to const, because sometimes we don't want to modify the value of the object from this pointer; however, you cannot assign a const object to a non-const pointer, because it may change the value pointing to the object through this pointer, but there is also a way to make this operation legal, you can use the pointer to change the const object through forced type conversion:
Const int r = 100;
Int * ptr = const_cast (& r); // C standard, C language: int * ptr = (int *) & r;

4. For character Arrays
Statements such as char * name = "china"; can be passed during compilation, but "china" is a constant character array, any operation that you want to modify can also be compiled but may cause runtime errors. If you want to modify the character array, use the char name [] = "china"; format.

V. Functions
1. void Fuction1 (const int r); // The const value is passed for the parameter, meaning that the initial value of the variable cannot be changed by the function.

2. const int Fuction1 (int); // The returned const value indicates that the initial value of the variable in the returned original function cannot be modified, but the variable returned by the function by value is copied, it makes no sense if it can be modified. It can be assigned to any const or non-const type variable without the need to add this const keyword. However, this is only for the internal type (because the internal Type Returns a value without returning a variable and is not used as the left value). For the user-defined type, the return value is a constant. For more information, see section 3.

3. Class CX; // there is an internal constructor, such as CX (int r = 0)
CX Fuction1 () {return CX ();}
Const CX Fuction2 () {return CX ();}
As shown in the preceding custom class CX, and functions Fuction1 () and Fuction2 (), when we perform the following operations:
Fuction1 () = CX (1); // No problem. It can be called as the left value.
Fuction2 () = CX (1); // compilation error. The return value of const cannot be called as the left value. Because the left value uses the return value as a variable to modify its return value, the const statement prohibits this modification.

4. Pass and return the const of the pointer in the function:
Int F1 (const char * pstr); // when passed, you can use the const modifier to ensure that the initial values of the passed parameters are not modified using this pointer, any attempt to modify * pstr in the function will cause a compilation error.
Const char * F2 (); // indicates that the pointer returned by the function points to a const object, which must be assigned a pointer to the const object.
Const char * const F3 (); // a const is used more than the preceding one. This const is valid only when it is used as the left value, it indicates that this pointer cannot be modified in addition to pointing to a const object, so it cannot be processed as a left value.
5. Transfer the const referenced in the function:
Void F1 (const X & px); // The effect of passing a const reference is the same as that of passing the most common function by value, it prohibits all modifications to the referenced object. The only difference is that by passing the value, a copy of the class object will be created first, and then passed in, and it will directly pass the address, therefore, this transfer is more effective than passing by value.
** In addition, only the referenced const can be passed to a temporary object. Because the temporary object is a const attribute and is invisible, it exists in a local domain for a short time, So pointers cannot be used, only the referenced const pass can capture this guy.

6.
1. First, the const member variables can only be initialized in the const using the initialization member list. Attempting to initialize the const member variables in the const body will cause compilation errors. The list of initialized members is shown in the following figure:
2. X: X (int ir): r (ir) {}// assume that r is a const member variable of class X.

2. const member function. To mention this concept, we should first talk about the const object, just as the built-in type can define the const object (const int r = 10 ;), the user-defined type can also define the const object (const X px (10);). The compiler must ensure that this object cannot be changed within its lifecycle. If you define such a const object, the compiler will disable all non-const member functions of this object and report errors during compilation to ensure the const feature of the object. So if you want your member functions to operate on the const object, you need to declare this function as a const member function. If f () is a member function in the class, its declaration is like:
Int f () const; // put const at the end of the function. The Compiler checks this function, any operation in this function that tries to change the member variable or call a non-const member function is considered invalid.
Note: neither class const nor destructor can be const functions.

3. a const member function is created, but you still want to use this function to change the data in the object. Such a requirement is also frequently met, especially in a demanding interview Examiner. First, we need to clarify the requirements of the examiner, because there are two ways to achieve this. If the examiner asks not to change anything in the original class, you only need to start with the current const member function, then you only need to use the type forced conversion method mentioned above. Example:
// Assume there is a class named X, which has an int member variable r. We need to use a const member function f () to perform r operations on this r. The Code is as follows:
Void X: f () const
{(Const_cast (this)-> r;} // use the this pointer to forcibly convert the type.
Another method is to use the keyword mutable. If your member variables look like this during definition:
Mutable int r;
Then it tells the compiler that the member variable can be changed through the const member function. The compiler will no longer care about his check.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.