I don't know the exact meaning of the reference and its use.

Asked 2 years ago, Updated 2 years ago, 45 views

class point
{
private:
    int* arr;
    int len;
public:
    point(int a)
        :len(a)
    {
        arr = new int[len];
    }
    int& operator[](int a)
    {
        if (a<0 || a>=len)
            exit(1);
        else
            return arr[a];
    }

};
int main()
{
    point p(3);
    for (int i = 0; i < 3; i++)
        p[i] = i;

    return 0;
}

When I do this, the compilation works well

class point
{
private:
    int* arr;
    int len;
public:
    point(int a)
        :len(a)
    {
        arr = new int[len];
    }
    int operator[](int a)
    {
        if (a<0 || a>=len)
            exit(1);
        else
            return arr[a];
    }

};
int main()
{
    point p(3);
    for (int i = 0; i < 3; i++)
        p[i] = i;

    return 0;
}

When you do this,

 p[i] = i;

In this part, the expression displays an error as lvalue that cannot be modified. I wonder why compilation errors appear if I don't attach a reference because of the reference next to int.

reference

2022-09-20 11:30

1 Answers

int operator[](int a);

The code above is int in the form of the return value of the function. Because the function returns by default by value, the int-type value is returned to the place where this function was called. In other words, p[i] returns an int-type number.

Therefore, the reason for the error in p[i]=i; is that int-type number is returned as a result of p[i] Like number=i;, it became a code to substitute another number for a number, so the error "number is not lvalue" appeared.

int& operator[](int a);

On the other hand, if you add a reference (&) after the int as above, it means that the value you want to return is a declared variable (whether it has a name or not), and the place where the return value is sent (the called place) is a nickname for the already declared variable (the value you want to return). The question code returns the ath of the class's member variable, arr. Therefore, p[i]=i; is the nickname of arr[i]=i;.


2022-09-20 11:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.