【问题标题】:[] Operator overloading for get and set operation in c++[] C++ 中 get 和 set 操作的运算符重载
【发布时间】:2015-11-26 10:50:03
【问题描述】:

我正在上以下课程:

class mem
{
private:
    char _memory[0x10000][9];

public: 
    const (&char)[9] operator [] (int addr);    
}

我的目标是能够像数组一样使用mem 类,而稍后实现会更复杂。所以,我应该可以

  • 像“mem[0x1234]”一样访问它以返回对 9 个字符数组的引用
  • 像 'mem[0x1234] = "12345678\0";' 一样写入它

这是我尝试过的:

#include "mem.h"

const (&char)[9] mem::operator [] (int addr)
{
    return &_memory[addr];
}

但是,它说该方法“必须有一个返回值”,我认为我已将其定义为 (&char)[9],但作为此定义,我收到错误消息“预期标识符”。

【问题讨论】:

    标签: c++ arrays reference operator-overloading


    【解决方案1】:

    operator[] 是一个接受 int 的函数

    operator[](int addr)
    

    返回引用

    & operator[](int addr)
    

    到一个长度为 9 的数组

    (&operator[](int addr))[9]
    

    const char

    const char (&operator[](int addr))[9]
    

    也就是说,不要那样做。使用typedefs 来简化:

    typedef const char (&ref9)[9];
    ref9 operator[](int addr);
    

    也就是说,不要那样做。

    std::array<std::array<char, 9>, 0x10000> _memory;
    const std::array<char, 9>& operator[](int addr);
    

    【讨论】:

      【解决方案2】:

      如下写法

      #include "mem.h"
      
      const char ( & mem::operator [] (int addr) const )[9]
      {
          return _memory[addr];
      }
      

      你也可以添加一个非常数运算符

      char ( & mem::operator [] (int addr) )[9]
      {
          return _memory[addr];
      }
      

      类定义如下所示

      class mem
      {
      private:
          char _memory[0x10000][9];
      
      public: 
          const char ( & operator [] (int addr) const )[9];    
          char ( & operator [] (int addr) )[9];    
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 2012-08-08
        • 2012-11-26
        • 1970-01-01
        相关资源
        最近更新 更多