References to C + +

Source: Internet
Author: User

A reference in C + + is the equivalent of an alias to a variable.

       int a,j=3;       int &b=a;       B=j;

where b appears, it is equivalent to a, and b is replaced by a.

Attention:

1. References must be initialized at the time of declaration.

2. After initialization, the reference is the equivalent of that variable. And this app can no longer point to other variables.

3. The reference itself does not occupy memory and the system does not allocate memory.

4. A reference to an array:

       int a_a[10]={0};       int (&a_b) [10]=a_a;

In fact: 1 and 2 sum up a bit like a constant pointer.

       int &b=a;       int * Const c=&a;
like C and B, declarations must be initialized.

Like C and B, you can no longer point to other content.

An interesting thing to do:

When can an already initialized reference point to another variable? To judge the correctness of 2.

Class A{public:a (int& _a): A (_a) {}private:int& A;}; int main () {       int i=1,j=2;       Aa (i);       Ab (j);       a=b;   Error       System ("pause");       return 0;}

This is interesting, A's a is a reference to I, B's A is a reference to J, A=b assignment operation, the system thinks we want to change a to a reference to J. It is illegal to do so.

Think: The system-provided assignment operation is not A.A=B.A? And this is obviously legal.

In fact, the system provides the default assignment operation is not simply the variable and variable =, so simple ah.

When a member variable of a class is a reference,

1> This variable must be assigned a value in the constructor's initialization list and cannot be assigned a = sign within the constructor function.

Class a{public:a (int i): b (i) {}private:int & B;};

2> the object of this class is not assignable. As in the above example.

References to C + +

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.