c++ - 错误 : invalid initialization for struct in C++

标签 c++ struct compiler-errors initialization constants

错误:

invalid initialization of reference of type Assoc<float, std::basic_string<char> >& from expression of type const Assoc<float, std::basic_string<char> >

对于这段代码

Assoc<keyType,valueType>& found = internalStorage.get(find(key));//returns the value of some key

对不起你们,我知道这没意思,但我很困惑。

知道问题出在哪里吗?

最佳答案

看起来像internalStorage.get()按值返回对象,而您正试图绑定(bind)一个非 const对返回的临时文件的引用。

解决此问题的最佳方法取决于您要执行的操作(以及 internalStorage 的类型):

  • 如果不需要修改found , 引用const (参见 Does a const reference prolong the life of a temporary?)。
  • 如果确实需要修改found (这是存储在 internalStorage 中的拷贝),只需删除 & .
  • 如果需要修改存储在internalStorage中的对象,您可能需要重构代码。

关于c++ - 错误 : invalid initialization for struct in C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22088571/

相关文章:

c - 为什么 C 不允许结构中存在成员函数?

android - NotificationCompat.Builder 和 ActionBarSherlock 的问题

c - sizeof 对结构的不完整类型的无效应用

c++ - 具有多个函数的 Py_InitModule - 从 int 到 PyCFunction 的无效转换

c++ - 在无向树中寻找最长路径

directx 的 C++ 智能指针

c - 结构给我 "expression must be modifiable value"

c# - Lambda 分配局部变量

java - 反编译的代码导致 “Cannot reference a field before it is defined”

c++ - makefile 为不工作的目标文件创建自己的目录