C++使用[]赋值

class Test 
{
public:
    const int& operator[]( const int& index) 
    {
        std::cout << "[]" << std::endl;
        return 2;
    }
    int& operator[]( int&& index)
    {
        std::cout << "[][]" << std::endl;
        int j = 3;
        return j;
    }
    const int& operator=(const int& index) 
    {
        std::cout << "=" << std::endl;
        return 3;
    }
    friend std::ostream& operator<<(std::ostream& out, const Test&)
    {
        out <<1 << endl;
        return out;
    }
};
int main () 
{
    Test t;
    const int i = 12;
    int k = t[1] = i;
    cout << k << endl;
    cout << t[i] << endl;
  return 0;
} 

代码:

t[1] = i;

会调用参数为int && 的[]重载函数,也就是

int& operator[](int&& index)
    {
        std::cout << "[][]" << std::endl;
        int j = 3;
        return j;
    }

注意此函数不能返回const int&,因为不能给一个const赋值。

这句话的含义是 先t[1],然后赋值i

原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/11267305.html