Use of const in c ++

Source: Internet
Author: User

Use of const in c ++

In c ++, const is such a thing: if you want something that someone else cannot modify, it will take effect.

The usage of const is as follows:

A. Modify Constants

Const int;

Int const;

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

B. Modify the pointer:

Const double * p -- before the const pointer *, it indicates that the memory pointed to by the current pointer cannot be changed.

Double * const p -- after the const is placed on the pointer *, it indicates that the current pointer cannot be changed.

Const double * const p -- the current pointer and the memory pointed to by the pointer cannot be changed.

C. Modify parameters

Void funcA (const TYPE Value) {}-- const modifier parameter, indicating that this parameter cannot be changed in the function body.

D. Modify the function return value

Const int fun1 () {} -- const modifies the return value of the function. Therefore, constint result = fun1 () is required during the call, which indicates that the return value cannot be changed.

E. Modify member functions

Class

{

Void func () const;

// Const modifies A member function, which means that the function cannot modify the member variables in Class A. For example, you just want to get A value in Class A instead of changing it, it is helpful for program robustness.

}

If the blog description is incorrect 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.