【问题标题】:Overloaded bracket operator that calls nonstatic functions调用非静态函数的重载括号运算符
【发布时间】:2018-01-29 22:13:22
【问题描述】:

我有一个类可以读取/写入外部随机存取存储器。

.h 文件:

class RAM {
private:
  bool Read(char *Buffer, size_t BytesToRead, uint32_t StartAddress);
  bool Write(char *Buffer, size_t BytesToWrite, uint32_t StartAddress);

  class proxy {
  private:
    size_t _index;
  public:
    proxy(size_t i);
    void operator=(char rhs);
    operator char();
  }

public:
  proxy operator[](size_t i);
};

.cpp 文件:

RAM::proxy RAM::operator[](size_t i) {
  return proxy(i);
}

proxy::proxy(size_t i) {
    _index = i;
}

void proxy::operator=(char rhs) {
  Write(&rhs, 1, _index);  // error
}

RAM::proxy::operator char() {
  char Buf[1];
  Read(Buf, 1, _index);   // error
  return Buf[0];
}

Read 和 Write 是处理对 RAM 的低级访问的函数。没有其他方法可以读取或写入 RAM。我尝试使用proxy class in rvalue - how to implement assignment operator?,但无法毫无错误地适应它:

错误:在没有对象 Write(&rhs, 1, _index) 的情况下无法调用成员函数 'bool RAM::Write(char*, size_t, uint32_t)'

错误:无法在没有对象 Read(Buf, 1, _index) 的情况下调用成员函数 'bool RAM::Read(char*, size_t, uint32_t)'

还有其他需要读取和写入的东西,所以我可能无法将它们设为静态。我还认为在创建 RAM 对象时它们已经被实例化了。

【问题讨论】:

  • 如何从公共函数返回私有类型的对象?
  • 你正在调用 RAM::Write 来自类 proxy,它不是它的成员。
  • 你的 Read, Write 函数应该是静态的。
  • proxy 类型的对象和RAM 类型的对象之间没有内在联系。为了调用RAM 对象的成员函数,proxy 对象必须具有指向RAM 对象的指针或引用。只需添加一个,并在创建proxy 对象时对其进行初始化。
  • @RichardCritten 类代理是 RAM 类的子类。它应该可以访问所有 RAM 类的函数和变量。

标签: c++


【解决方案1】:

感谢 PeteBecker,我能够想出一个有效的代码。另外,我在最初的问题中没有问,但我忽略了测试直接分配,结果证明这是一个不同的野兽。

class RAM {
private:
  // changed 1st arg to void*, because type doesn't really matter.
  bool Read(void *Buffer, size_t BytesToRead, uint32_t StartAddress);
  bool Write(void *Buffer, size_t BytesToWrite, uint32_t StartAddress);

  class proxy {
  private:
    size_t _index;
    RAM *_parentPtr;  // <-- added

  public:
    proxy(size_t i, RAM *ptr) {
      _index = i;
      _parentPtr = ptr;  // <-- added
    }  
    void operator=(char rhs) {
      Write(&rhs, 1, _index);  // works now
    }
    void operator=(proxy rhs) {  // new function for direct assignment
      char temp = rhs;
      Write(&temp, 1, _index);
    }
    operator char() const {
      char Buf[1];
      Read(Buf, 1, _index);   // works now
      return Buf[0];
    }
  }

public:
  proxy operator[](size_t i) {
    return proxy(i, this);
  }
};

我花了很长时间才弄清楚我必须通过一个临时变量请求 rhs 的值才能执行operator char() const。作为参考传递不会这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2012-10-02
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多