2017-09-03 71 views
0

我是C++的初學者,所以很可能我的問題非常容易解決。 我的問題是,我試圖在我的頭文件中聲明一個數組,但是我無法在main.cpp單元中訪問它。 ,保持印刷錯誤信息是:「初始化:不能從‘詮釋’轉換爲‘廉政[6]’在頭文件中聲明的C++ extern數組在main.cpp中不可用

這是在我的頭文件中的代碼:

#pragma once 

extern int Guess[6] = 0; 

void Input(){ 
    std::cout << "Please enter your 6 numbers in the range of 1-49 line by line:" << std::endl; 
    for (int i = 0; i < 6; i++){ 
     std::cin >> Guess[i]; 
     for (int i1 = 0; i1 < 6; i1++){ 
      if (Guess[i1] > 50){ 
       std::cout << "Your number is not in the range!!! Try again please:" << std::endl; 
       Guess[i1] = 0; 
       std::cin >> Guess[1]; 

      } 
     } 

    } 

    std::cout << Guess[0] << std::endl; 
    std::cout << Guess[1] << std::endl; 
    std::cout << Guess[2] << std::endl; 
    std::cout << Guess[3] << std::endl; 
    std::cout << Guess[4] << std::endl; 
    std::cout << Guess[5] << std::endl; 
} 

這是代碼在main.cpp

#include "stdafx.h" 
#include <iostream> 
#include "Input.h" 

int main(){ 

    int Guess[6]; 
    Input(); 
    return 0; 
} 

感謝任何潛在的幫助

+2

在main()函數體外部移動'int Guess [6];'並在聲明中放入'= 0'。 – user0042

+0

如果您使用的是標題,則只需在其中包含聲明或內聯定義。 「猜測」和「輸入」只應聲明,其定義放在單獨的「cpp」文件中;特別是將'= 0'部分放在'Guess'上。 – Cubic

+1

而不是數組使用std :: array 並將其作爲參數(通過引用)傳遞給您的函數 - 因此您將不需要外部變量或全局變量 –

回答

1

你不應該初始化外部陣列,但只能向前聲明它所以喲。 ü可以像這樣把它聲明:

extern int Guess[6]; 

而在另一個文件中,你應該在全球範圍進行定義:

//source.cpp 

int Guess[6]; // Remove the keyword `extern` here and you must specify the size here. 

void DoSomeThing(){ 

    // now you can use it here 
    Guess[0] = 0; // eg 
} 
  • 您也可以聲明外部陣列時不指定大小:

    // input.h 
    
    extern int bigIntArray[]; 
    
    // source.cpp 
    
    int Guess[6]; 
    
    void DoSomething(){ 
    
        // Do some staff on the array. 
    } 
    

這通知編譯器th e數組在其他地方定義。

+0

非常感謝您的幫助! –