簡體   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