C + + Const qualifier

Source: Internet
Author: User

    • Basic Features
    1. A const object must be initialized once it has been created and its value cannot be modified.
    2. You can initialize a const object with a non-const object, or you can assign a const object to a non-const object
    • By default, const objects are only valid within a file
    1. When a const variable with the same name appears within multiple files, it is equivalent to defining a separate variable in a different file
    2. To share a const object between multiple files, add the extern keyword before the definition of the variable
    • & Type and const
1.The & (Reference) type differs from the * (pointer) type,The declaration, definition, and initialization of a reference type are together, and no other variables can be referenced after initialization            there is no limit to the declaration, definition, initialization, and subsequent assignment of pointer types.
  
 
  1. int a = 1;
  2. int b = 2;
  3. int &c = a;
  4. int *p;
  5. p = &a;
2, with the const collocation
  
 
  1. int a = 1;
  2. int b = 2;
  3. /**< 因为引用在被初始化之后就不能在引用其它变量,所以没有int & const c = a这种写法 */
  4. const int &c = a;
  5. /**
  6. * 不能给c赋值,对a无要求(a可以是const或者非const类型,a也可以重新赋值)
  7. * 不能将c赋值给非const类型
  8. */
  9. const int *p1 = &a;//等同于int const *p1 = &a;
  10. /**
  11. * 底层const
  12. * 不能通过p1修改a的值,对a无要求
  13. * 不能将p1赋值给非const类型
  14. * p1可以指向其他变量
  15. */
  16. int * const p2 = &a;
  17. /**
  18. * 顶层const
  19. * 可以通过p2修改a的值
  20. * p2不能指向其他变量
  21. */
  22. const int * const p3 = &a;
If the const is located in*, the const is used to modify the variable pointed to by the pointer, that is, the pointer to a constant;
If the const is located in*on the right, const is the modifier pointer itself, that is, the pointer itself is a constant.


From for notes (Wiz)

C + + Const qualifier

Related Article

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.