C 外部阵列在标头中声明,在main.cpp中不可用



我是C 的初学者,因此我的问题很容易解决。我的问题是我试图在标题文件中声明一个数组,但是我可以在main.cpp单元中加以将其加以操作。不断打印的错误消息是:"初始化:无法从'int'转换为'int [6]'

这是我的标题文件中的代码:

#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;
}

感谢您的任何潜在帮助。

您不应初始化外部数组,而应向前声明它。因此,您可以这样声明:

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.
    }
    

此通知编译器,将数组定义在其他地方。

相关内容

最新更新