繁体   English   中英

C++ 运算符返回差异

[英]C++ Operator return difference

任何人都可以解释这个 [] 运算符的两个版本之间的区别(如果有的话)? 两个版本都运行良好...

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];

首先,您必须使您的操作员可访问:

class Test {
private: 
    int arr[100];

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

现在,这不会编译(因为arr是私有的):

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

int operator[](int i)按值返回( rvalue ),使a[5] = 10; 不可能的。

int& operator[](int i)返回对存储在arrlvalue )中的int的引用,这使得a[5] = 10; 可能的。

但它不会编译,因为您的运算符仅在返回类型( intint& )上有所不同。 使一个按值返回const解决了这个问题:

#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);
}

输出:

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

首先,您必须使您的操作员可访问:

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
};

上述两个运算符之间的区别是 -

情况 1 -> 您只能将其用作 R 值。

情况 2 -> 您可以将其用作“R 值”和“L 值”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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