类型引用的初始化无效

invalid initialization of reference of type

本文关键字:无效 初始化 引用 类型      更新时间:2023-10-16

在我的代码(不是我的)中有一个函数isInstruction(),用于设置和获取成员,没有问题。现在我为类似的目的添加了我自己的函数state()。这样的:

struct foo {
  bool & isInstruction() {
    return isInst;    // no problem
  }
  int & state() {
    return state;   //ERROR
  } 
private:
  bool isInst;
  int state;  
};

我对第一个函数没有问题。但是对于第二个,我得到

error: invalid initialization of reference of type ‘int&’ from expression of type 
‘<unresolved overloaded function type>’

那么问题是这两个函数有什么不同。我错过什么了吗?

不同之处在于两个实体(成员变量和成员函数)共享相同的名称state,这就是导致问题的原因。

尝试重命名其中一个

相关文章: