簡體   English   中英

c++ 中的 scope 錯誤中未聲明變量?

[英]Variable is not declared in the scope error in c++?

我是 c++ 中的新蜜蜂,我將使用 for 循環迭代整數,但出現錯誤

               error: ‘frame’ was not declared in this scope
               auto position_array = (*frame)[i][j];

但是正如您在下面的代碼中看到的那樣,它被聲明為

    auto ds = data_file.open_dataset(argv[1]);
    // auto frame = data_file.read_frame(ds, 0); // inside the loop
    for (int i = 0; i < 3; ++i)
        auto frame  = data_file.read_frame(ds, i);

    for (size_t i = 0; i < nsamples; ++i) {
        for (size_t j = 0; j <= 2; ++j) { // j<=2 assign all columns 
            auto position_array = (*frame)[i][j];
        }
        corr.sample(frame);
    }
    corr.finalise();

如果我使用注釋的第二行,它工作正常。 但是現在我想遍歷data_file.read_frame(ds, i)的第二個變量並且出現錯誤? 我究竟做錯了什么? 我需要聲明int frame = 0; 在for循環之前? 為簡潔起見,我只是發布帶有錯誤的代碼,以防有人需要查看整個代碼,歡迎您!

聽起來你需要一個嵌套的 for 循環。 使用

for (int i = 0; i < 3; ++i)
{
    auto frame  = data_file.read_frame(ds, i);

    for (size_t j = 0; j < nsamples; ++j) {
        for (size_t k = 0; k <= 2; ++k) { // j<=2 assign all columns 
            auto position_array = (*frame)[i][j];
        }
        corr.sample(frame);
    }
}

讓您獲取每一frame ,然后處理每一幀的每個元素。

這個for循環

for (int i = 0; i < 3; ++i)
    auto frame  = data_file.read_frame(ds, i);

相當於

for (int i = 0; i < 3; ++i)
{
    auto frame  = data_file.read_frame(ds, i);
}

那是 for 循環 forms 它的一個 scope 的子語句。 在 scope 之外,變量框架不可見。

此外,在循環的每次迭代中都會重新創建變量frame

來自 C++ 17 標准(9.4 選擇聲明)

  1. ...選擇語句中的子語句(每個子語句,以 if 語句的 else 形式)隱式定義了塊 scope (6.3)。 如果選擇語句中的子語句是單個語句而不是復合語句,就好像它被重寫為包含原始子語句的復合語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM