[英]Initialize a vector properly
struct the_raw_data {
double data;
double other;
};
int testingReadFunctionsout() {
std::vector<the_raw_data> &thevector; /*Here is where the initialization needs to happen*/
return 0;
}
I am getting the following error:我收到以下错误:
main.cpp: In function ‘std::vector<the_raw_data>& readDataFromFileOut(std::__cxx11::string)’: main.cpp:108:29: error: ‘v’ declared as reference but not initialized std::vector<the_raw_data>& v;
The error is self-explanatory:错误是不言自明的:
'v' declared as reference but not initialized
'v' 声明为引用但未初始化
You have declared a variable v
that is a reference , but it does not reference anything:您已经声明了一个变量
v
是一个reference ,但它没有引用任何东西:
std::vector<the_raw_data> &thevector; // what is thevector pointing at? NOTHING!
You can't have uninitialized references in C++.在 C++ 中不能有未初始化的引用。 A reference is just an alias for another object, so you have to initialize it to point at something (in practical terms, think of a reference as being like a pointer that can never be NULL, because that is how most compilers actually implement it), eg:
引用只是另一个对象的别名,因此您必须对其进行初始化以指向某个对象(实际上,将引用视为永远不能为 NULL 的指针,因为大多数编译器实际上是这样实现的) ,例如:
std::vector<the_raw_data> &thevector = SomeOtherObject;
Where SomeOtherObject
is another std::vector<the_raw_data>
object elsewhere in memory.其中
SomeOtherObject
是内存中其他地方的另一个std::vector<the_raw_data>
对象。
If you want v
to be an actual std::vector<the_raw_data>
object of its own, just get rid of the &
in the variable declaration:如果您希望
v
成为它自己的实际std::vector<the_raw_data>
对象,只需去掉变量声明中的&
:
std::vector<the_raw_data> thevector;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.