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;
}
感謝任何潛在的幫助
在main()函數體外部移動'int Guess [6];'並在聲明中放入'= 0'。 – user0042
如果您使用的是標題,則只需在其中包含聲明或內聯定義。 「猜測」和「輸入」只應聲明,其定義放在單獨的「cpp」文件中;特別是將'= 0'部分放在'Guess'上。 – Cubic
而不是數組使用std :: array並將其作爲參數(通過引用)傳遞給您的函數 - 因此您將不需要外部變量或全局變量 –