在 C++ 标头中声明数组并在 cpp 文件中定义它?

2022-01-11 00:00:00 arrays header c++ declaration

这可能是一件非常简单的事情,但我是 C++ 新手,所以需要帮助.

This is probably a really simple thing but I'm new to C++ so need help.

我只想在我的 C++ 头文件中声明一个数组,例如:

I just want to declare an array in my C++ header file like:

int lettersArr[26];

然后在 cpp 文件中的函数中定义它,例如:

and then define it in a function in the cpp file like:

    lettersArr[26] = { letA, letB, letC, letD, letE, letF, letG, letH,
        letI, letJ, letK, letL, letM, letN, letO, letP, letQ, letR, letS,
        letT, letU, letV, letW, letX, letY, letZ };

但这不起作用.

是我的语法错误还是什么?正确的方法是什么?

Have I got the syntax wrong or something? What is the correct way to to this?

非常感谢.

推荐答案

在头文件的声明中添加extern.

Add extern to the declaration in the header file.

extern int lettersArr[26];

(另外,除非您打算更改数组,否则请考虑添加 const.)

(Also, unless you plan to change the array, consider also adding const.)

定义必须有类型.添加int(或const int):

The definition must have a type. Add int (or const int):

int lettersArr[26] = { letA, /*...*/ };

相关文章