非常量引用类型的无效初始化中出错.在Linux操作系统中使用c++代码.GCC编译器

error in invalid initialization of non-const reference type . Using c++ code in Linux OS. GCC Compiler

本文关键字:操作系统 c++ 编译器 GCC 代码 Linux 引用类型 常量 无效 出错 初始化      更新时间:2023-10-16

vector<string>& temp = var_obj.funct();在Linux中不工作,但&除外,它工作正常。vector<string> temp = var_obj.funct();

错误:类型的非常量引用的初始化无效'std::vector,std::分配器>,std::分配程序,std::分配器>>&'从临时类型为"std::vector",std::allocater>,std::分配器,std::分配器>>'

问题是函数返回的值是临时的。您无法生成对它的引用,因为它只是暂时存在的。函数调用后,该值将消失。

相反,试试这个:

vector<string> temp = var_obj.funct();
vector<string> &temp2 = temp;

现在您有了一个名为temp2的引用。