繁体   English   中英

正确初始化向量

[英]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;
}

我收到以下错误:

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;

错误是不言自明的:

'v' 声明为引用但未初始化

您已经声明了一个变量v是一个reference ,但它没有引用任何东西:

std::vector<the_raw_data> &thevector; // what is thevector pointing at? NOTHING!

在 C++ 中不能有未初始化的引用。 引用只是另一个对象的别名,因此您必须对其进行初始化以指向某个对象(实际上,将引用视为永远不能为 NULL 的指针,因为大多数编译器实际上是这样实现的) ,例如:

std::vector<the_raw_data> &thevector = SomeOtherObject; 

其中SomeOtherObject是内存中其他地方的另一个std::vector<the_raw_data>对象。

如果您希望v成为它自己的实际std::vector<the_raw_data>对象,只需去掉变量声明中的&

std::vector<the_raw_data> thevector;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM