Const detail in C + +

Source: Internet
Author: User

Const detail in C + +

From http://blog.csdn.net/lwbeyond/article/details/6187501

I. The role of cons

(1) const constants can be defined

    1. const int max=100;
    2. int Array[max];

(2) Can protect the modified things, prevent accidental modification, enhance the robustness of the program

If I is modified in the function body, the compiler will make an error;

    1. void f (const int i)
    2. {
    3. i=10;   //error!
    4. }

(3) provides a reference for function overloading


    1. Class A
    2. {
    3. ......
    4. void f (int i) {...} //a function
    5. void f (int i) const {...} //overload of previous function
    6. ......
    7. };

(4) can save space and avoid unnecessary memory allocation

  1. #define PI 3.14159//Macro Constants
  2. Const DOULBE pi=3.14159; //The PI is not placed in ROM at this time
  3. ......
  4. Double I=pi;  //Allocate memory for PI at this time, no longer assign!
  5. Double I=pi; //macro substitution during compilation, allocating memory
  6. Double J=pi; //No memory allocation
  7. Double J=pi;  //Replace the macro again and allocate memory again!


Const definition constants from the assembly point of view, just give the corresponding memory address, instead of the immediate number as given in # define, so the const definition of the constant in the program runs only one copy, and the constant defined by the # # has several copies in memory.

(5) Improved efficiency
The compiler typically does not allocate storage space for ordinary const constants, but instead saves them in the symbol table, which makes it a constant during compilation, without the storage and read memory operations, making it highly efficient.

Two. Using the const
(1) Modifier general constants, constant groups, regular objects
The modifier const can be used before the type specifier, or it can be used in the type description specifier. For example:

  1. Constant
  2. int const x=2;
  3. const int x=2;
  4. Constant group
  5. int Const A[5]={1, 2, 3, 4, 5};
  6. const int A[5]={1, 2, 3, 4, 5};
  7. Constant object
  8. Class A;
  9. const A;
  10. a const A;

(2) Modifier pointer

    1. const int *a;
    2. int const *A; //const the object to which the modifier is directed, a variable, the object a points to is immutable
    3. int *const A; //const modifier Pointer A, a is immutable, the object a points to is variable
    4. const INT *const A; //The objects pointed to by pointer A and a are immutable


<<effective c++>> has a good way to remember: the const on the left side of the * number is the pointer of the content, the const on the right side of the number is a pointer.
Simple note is: Left content, right pointer.

You can also understand: ignore the type name first, and then see where the const is near, and modify who.

such as: const [INT] *p; First the int is removed, then the const modifier *P, p is the pointer, and *P is the object pointed to by the pointer, not variable

(3) Modifier reference

    1. Const Double & V; //The object referenced by the reference cannot be updated

(4) The return value of the modifier function

The const modifier can also modify the return value of the function, and the return value cannot be changed in the following format:

    1. const int Fun1 ();
    2. Const MyClass FUN2 ();

(5) member functions for decorated classes
The const modifier can also decorate a member function of a class, in the following format:

    1. Class ClassName
    2. {
    3. Public
    4. int fun () const;
    5. .....
    6. };


In this way, the data inside the class cannot be modified when the function fun is called.

    1. Class A
    2. {
    3. Public
    4. A (int i=0): Test (i) {} //Initialize list
    5. Private
    6. const int i

(6) To reference a const constant in another connection file

    1. extern const int i; //Correct reference
    2. extern const int j=10; //Error! Constants cannot be assigned again


Three. A few issues to be explained
(1) How do I initialize a constant inside a class?
Method 1: Initialize the list:

    1. Class A
    2. {
    3. Public
    4. A (int num): I (NUM) //with num to initialize I
    5. {};
    6. Private
    7. const int i;
    8. };

Method 2: External initialization


    1. Class A
    2. {
    3. Public
    4. A () {}
    5. Private
    6. static const int i; //Note must be static
    7. };
    8. const int a::i=3; //External initialization


(2) What are the limitations of constants placed inside a class?

  1. Error
  2. Class A
  3. {
  4. Public
  5. A ()
  6. {};
  7. Private
  8. const INT c1 = 7; //error
  9. static const INT c2 = 7; //error
  10. static int c3 = 7; //error
  11. }
  12. Correct
  13. Class A
  14. {
  15. Public
  16. A (int num): C1 (num)
  17. {};
  18. Private
  19. const INT C1;
  20. static const INT c2;
  21. static int c3;
  22. }
  23. const INT a::c2 = 7; //Do not add static
  24. int a::c3 = 7; //Don't add STATCI

Here are three correct initialization methods, note that static cannot be added to the static flag when it is initialized externally.

3) is const an overloaded reference object?
Let's look at an example:


    1. Class A
    2. {
    3. ......
    4. void f (int i) {...} //a function
    5. void f (int i) const {...} //overload of previous function
    6. ......
    7. };


The above is overloaded is no problem, then the following?

    1. Class A
    2. {
    3. ......
    4. void f (int i) {...} //a function
    5. void f (const int i) {...}  //???
    6. ......
    7. };

This is a mistake, the compilation does not pass. So is it that the const of the internal parameter is not overloaded?

Let's look at the following example:

    1. Class A
    2. {
    3. ......
    4. void f (int&) {...} //a function
    5. void f (const int&) {...}  //???
    6. ......
    7. };


This procedure is correct, it seems that the above conclusion is wrong. Why is that? This concerns the transparency of the interface.
When passing by value, this is transparent to the user, and the user does not know what the function does to the formal parameter, in which case overloading is meaningless, so the rules cannot be overloaded!

When a pointer or reference is introduced, the user will have a certain understanding of the operation of the function, is no longer transparent, the overload is meaningful, so the provisions can be overloaded.

Const detail in C + +

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.