c++ - 错误 : invalid initialization of non-const reference of type. ..来自临时类型

标签 c++ reference initialization constants pass-by-reference

<分区>

我想我可以像这样创建和填充 C++ 映射:

 39 int main(){
 40 
 41   cout << "Approximate travelling salesman path finder." << endl;
 42   cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl << endl;
 43 
 44   map<City, OtherCities> database; 
 45   ReadInData(&database);
 46   ... 
 47 }

作为旁注,ReadInData函数只需要一个 map<City, OtherCities>引用作为参数,其中 City只是字符串的类型定义(城市名称),并且 OtherCities是一个包含 (string, int) 对的优先级队列,这些对代表其他城市及其与第一个城市的距离。

无论如何,尝试编译它会导致以下错误:

pr3.cpp: In function ‘int main()’:
pr3.cpp:45: error: invalid initialization of non-const reference of type ‘std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> > > > >&’ from a temporary of type ‘std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::priority_queue<OtherCity, std::vector<OtherCity, std::allocator<OtherCity> >, std::greater<OtherCity> > > > >*’

我在这里做错了什么,以及(除了使用禁忌全局变量之外)还有另一种保持 database 的好方法吗?在主要功能中并在其他地方填充/使用它?我不想只按值传递它的拷贝...

最佳答案

如果函数需要一个引用,你应该传递 database , 不是 &database后者是 database地址 , 所以它是一个指针,而不是一个引用。

关于c++ - 错误 : invalid initialization of non-const reference of type. ..来自临时类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17079039/

相关文章:

c++ - 从 Rcpp 函数返回指向 `new` 对象的指针的正确方法

c++ - Boost.进程间 : testcase gives different results if compiled with or without optimization (GCC)

java - 静态初始化 block 和常规静态初始化之间的区别

c++ - 是否有用于从另一个不同的 std::array 初始化 std::array 的特定语法?

swift - 未分配的常量可选默认情况下不会为零

c++ - 理解 GCC 中的 std::pow 实现

c++ - *** 检测到 glibc *** ... : free(): invalid next size (normal): . ..*** 在 fclose() 之后;

java - 在java中,如何从jar文件中检索图像?

c++ - vector 引用 C++

rust - Rust 的确切自动解引用规则是什么?