对非常量的引用的初始值必须是 ctor 中的左值

问题描述 投票:0回答:0

我正在编写一个带有组件虚拟类的程序,该程序详细说明了需要通过总线访问设备上的寄存器的组件的行为。寄存器上的各种操作在虚拟类中描述,该虚拟类与所使用的总线类型无关。派生的 RegisterI2C 类实现 I2C 总线的寄存器访问功能。 ComponentI2C 类对应于使用 I2C 总线的组件的使用。在这个类中,我尝试定义component_reg函数,它调用RegisterI2C类的构造函数,但在编译时出现以下错误:

对非常量的引用的初始值必须是左值 C/C++(461)。

我尝试过不同类型的铸造,但尚未找到解决方案。因此,如果有人有想法,我将不胜感激:)

class Component;
class Register {  // defines access method to registers
 public:
  Register(Component *parent, int reg) : parent_(parent), register_(reg) {}
  virtual int read() = 0;  // read the register
  Component *const parent_; // parent component
  int register_; // the register to operate on
};
class Component {  // defines what a component do.Uses Register functions
  virtual Register &component_reg(int reg) = 0; // return a Register we use for op on comp
};
class I2C {};  // provides I2C busfunctions
class ComponentI2C;
class RegisterI2C : public Register {  // implement Register func for I2C bus
 public:
  RegisterI2C(Component *parent, int reg) : Register(parent, reg) {}
/* use I2C class methods through downcasting Component to ComponentI2C */
  int read() override { return 0; }
};
class ComponentI2C : public Component, public I2C {
 public:
  Register &component_reg(int reg) override { return {this, reg}; }; // **PROBLEM HERE**
};

注意:返回 component_reg 作为指针不是一个选项:(

c++ casting initialization
© www.soinside.com 2019 - 2024. All rights reserved.