C + + references and pointers

Source: Internet
Author: User

Reference:
Defines a reference type in the form of a declarator written as &d, where D is the variable name.
1. A reference is not an object, it is simply an alias for an existing object.
2, the reference must be initialized, once the initialization is complete, the reference will be bound together with its initial value.
3. A reference can only be bound to an object and cannot be bound to the value of a literal or the result of an expression.
4. Typically, the referenced type is strictly matched to the object to which it is bound.
Exception:
Constant references:
Double x = 1.2;
const int &p = x;
Initializing a reference to a constant allows an arbitrary expression to be used as the initial value, as long as the result of the expression can be converted to a referenced type.


Pointer:
Defines a reference type in the form of a declarator written as *d, where D is the variable name.
1, the pointer is an object, no need to assign the initial value in the definition; A pointer defined within a block-level scope will have an indeterminate value if it is not initialized.
2. In general, the type of the pointer is exactly the same as the object he points to.
Exception:
Pointer to constant: cannot be used to change the value of the object it refers to.
int x = 1.2;
const int *P = &x;
A pointer to a constant is allowed to point to a very const object.
3. If the pointer points to an object, it is allowed to access the object using the dereference character (*);
Dereferencing A pointer results in the object being referred to, so if the result of the solution is assigned a value, that is, assigning a value to the object being referred to.


Const pointer:
A constant pointer, which must be initialized, and once initialized, its value (that is, the address stored in the pointer) cannot be changed.
Place * Before the const keyword to indicate that the pointer is a constant.
int x = 1;
int * Const P = &x; P will always point to X

C + + references and pointers

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.