gpt4 book ai didi

c++ - 在 header 中声明一个使用全局变量作为元素的数组?

转载 作者:行者123 更新时间:2023-12-02 10:03:27 31 4
gpt4 key购买 nike

我尝试使用全局变量作为数组的元素。
问题是编译器想在声明数组时知道整数常量值。我以为我的全局变量已经是 const int 了???

全局头文件“constants.h”

#ifndef CONSTANT_H
#define CONSTANT_H

namespace constants{
extern const int MY_ROW;
extern const int MY_COLUMN;
}
#endif // CONSTANT_H

定义全局“constants.cpp”
#include "constants.h"

namespace constants{
const int MY_ROW{55};
}

主要功能“main.cpp”
#include "constants.h"
#include <iostream>
#include <array>

int main()
{
std::cout<<constants::MY_ROW<<std::endl;
int my_int_array[constants::MY_ROW];
return 0;
}

到目前为止一切顺利,我可以使用全局变量作为元素在 main 中声明一个数组。

但是如果我在另一个头文件中尝试“同样的事情”,编译器会提示。

“测试.h”
#ifndef TEST_H
#define TEST_H
#include "constants.h"

class Test
{
public:
Test();
~Test();
void display_array();
private:
int test_array[constants::MY_ROW]; //error here???
};
#endif // TEST_H

错误信息:
**error: array bound is not an integer constant before ']' token|**

如果有人能给黑暗带来光明,我将不胜感激。

最佳答案

main() , 为 int my_int_array[constants::MY_ROW]; MY_ROW的值编译器不知道,因为它直到链接器阶段才被解析,所以 my_int_array不能在编译时分配,只能在运行时分配,并且仅当您使用支持可变长度数组的编译器时才分配(参见 Why aren't variable-length arrays part of the C++ standard?)。

但是对于 class Test ,这根本不是一种选择。您不能在类中使用 VLA,因为编译器需要预先知道所有成员的完整大小,以便为类的实例设置内存存储。但是编译器不知道数组的大小,因此无法编译该类。

要执行您正在尝试的操作,您需要直接在它们的声明中初始化常量,而不是用 extern 将它们分开。 ,例如:

#ifndef CONSTANT_H
#define CONSTANT_H

namespace constants{
const int MY_ROW = 55;
const int MY_COLUMN = ...;
}
#endif // CONSTANT_H

Define constant variables in C++ header

关于c++ - 在 header 中声明一个使用全局变量作为元素的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416171/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com