简体   繁体   中英

C++ Operator return difference

Can anybody explain the difference (if there is any) between the 2 versions of this [] operator? Both version are working fine ...

class Test {

    int arr[100];

    int operator[](int i) {
        return arr[i];
    }

    int & operator[](int i) {
        return arr[i];
    }
};


Test a;
a.arr[5] = 10;

// works for both versions:
int n = a[5];

First, you must make your operators accessible:

class Test {
private: 
    int arr[100];

public:
    int operator[](int i) {
        return arr[i];
    }    
    int& operator[](int i) {
        return arr[i];
    }
};

Now, this won't compile (since arr is private):

Test a;
a.arr[5] = 10;

int operator[](int i) returns by value (an rvalue ), making a[5] = 10; impossible.

int& operator[](int i) returns a reference to the int stored in arr (an lvalue ) which makes a[5] = 10; possible.

But it won't compile since your operators only differ on the return types ( int vs. int& ). Making the one returning by value const solves that issue:

#include <iostream>

class Test {
private:
    int arr[100];

public:
    int operator[](size_t i) const { // note the const
        std::cout << "using operator[]() const\n";
        return arr[i];
    }
    int& operator[](size_t i) {
        std::cout << "using operator[]() mutable\n";
        return arr[i];
    }
};

void test_const(const Test& t) {
    std::cout << t[5] << "\n";
}

int main() {
    Test a;
    a[5] = 10;
    std::cout << a[5] << "\n";
    test_const(a);
}

Output:

using operator[]() mutable
using operator[]() mutable
10
using operator[]() const
10

First, you must make your operators accessible:

class Test {
private: 
    int arr[100];

public:
    int operator[](int i) {
        return arr[i];
    }  // -> Case 1  
    int& operator[](int i) {
        return arr[i];
    } // ->Case 2
};

The difference between above two operators is -

Case 1 -> you can use it only as R value.

Case 2 -> you can use it as "R value" as well as "L value".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM