Use of const in C + +

Source: Internet
Author: User

In C + +, Const is such a thing: if you want to be able to have something that others cannot modify, then the const will work.

The const is used in the following situations:

A. Modifier constants

const int A;

int const A;

No matter where the const is placed, the effect is actually the same.

b. Modifier pointers:

A const double *p--const is placed before the pointer *, which represents the memory that the current pointer points to is immutable.

A double *const p--const is placed on the pointer *, which represents the current pointer is immutable.

Const Double *const p--The current pointer and the memory that the pointer is pointing to are immutable.

c. modifier parameters

void Funca (const TYPE Value) {}--const modifier parameter, which means that the parameter cannot be changed within the function body.

D. Modifier function return value

The const int fun1 () {}--const modifier function returns a value, then a constint result = FUN1 () is required in the call, and the function is to represent that the return value is immutable.

E. Modifying member functions

Class A

{

void func () const;

The const modifier member function, which means that the function cannot modify a member variable in Class A, for example, if you are just getting a value in a, and you do not want to change it, it is useful for the robustness of the program.

}

If the post describes something wrong or inaccurate, please point it out! Thank you!




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.