C++;标头中声明的外部数组在main.cpp中不可用 我是C++初学者,我的问题很容易解决。 我的问题是,我试图在头文件中声明一个数组,但无法在main.cpp单元中访问它。 持续打印的错误消息是:“正在初始化:无法从“int”转换为“int[6]”
这是我的头文件中的代码:C++;标头中声明的外部数组在main.cpp中不可用 我是C++初学者,我的问题很容易解决。 我的问题是,我试图在头文件中声明一个数组,但无法在main.cpp单元中访问它。 持续打印的错误消息是:“正在初始化:无法从“int”转换为“int[6]”,c++,arrays,visual-studio,C++,Arrays,Visual Studio,这是我的头文件中的代码: #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];
#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;
}
感谢您提供的任何潜在帮助。您不应该初始化外部数组,而应该只向前声明它。因此,您可以这样声明它:
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. }
这会通知编译器数组是在其他地方定义的。Move
int Guess[6];
在main()之外
函数体,并在声明中删除=0
。如果使用标题,则仅在其中包含声明或内联定义。Guess
和Input
仅应声明,其定义位于单独的cpp
文件中;尤其是在Guess上删除=0
部分代替数组使用STD::Adple,并将其作为参数(按引用)传递给函数——这样就不需要Extn或Global ValuabsGET一个合理的C++书籍了。非常感谢您的帮助!
// input.h
extern int bigIntArray[];
// source.cpp
int Guess[6];
void DoSomething(){
// Do some staff on the array.
}