zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    屏幕适配的简单介绍
    静态单元格
    BOOL的getter方法
    取消注册监听器
    自定义cell
    假适配
    cell的重用
    UITableView的简单使用
    UISrcoll控件简单介绍
    创建ios界面的三步骤
  • 原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/11267305.html
Copyright © 2011-2022 走看看