C++ C++;错误:字段的大小必须为常量
有人能告诉我如何解决以下问题吗C++ C++;错误:字段的大小必须为常量,c++,C++,有人能告诉我如何解决以下问题吗 clang++-7 -pthread -std=c++17 -o main createLibrary/configuration.cpp createLibrary/growbox.cpp createLibrary/helper.cpp createLibrary/httprequests.cpp main.cpp In file included from createLibrary/configuration.cpp:2: In file included
clang++-7 -pthread -std=c++17 -o main createLibrary/configuration.cpp createLibrary/growbox.cpp createLibrary/helper.cpp createLibrary/httprequests.cpp main.cpp
In file included from createLibrary/configuration.cpp:2:
In file included from createLibrary/configuration.h:1:
In file included from createLibrary/growbox.h:12:
createLibrary/httprequests.h:13:10: error: fields must have a constant size:
'variable length array in structure' extension will never be supported
char device[configuration::maxNameSize];
^
1 error generated.
我按照configuration.h
,httprequests.h
的顺序包含.h文件。我想在configuration.cpp
文件中配置所有必要的配置参数,但我得到了显示的错误。我做错了什么
配置.h
配置.cpp
httprequests.h
httprequests.cpp
像这样声明
maxNameSize
// configuration.h
class configuration
{
public:
static const int maxNameSize = 30;
...
};
无需在configuration.cpp中定义它
您的方式不会使maxNamesize
成为编译时常量
编辑,我假设配置
是一个类。如果它是一个名称空间,那么改为执行以下操作
// configuration.h
namespace configuration
{
const int maxNamesize = 30;
...
}
常量是“一个定义”规则的例外,因此可以在头文件中定义它们。外部常量int不是一个定义 变量在点p的常量表达式中可用,如果
- 变量是
- constexpr变量,或
- 它是一个常量初始化变量
- 参考类型或
- 常量限定整型或枚举型
- 变量的定义可以从P中得到
- 及
- P与变量定义在同一个转换单位中
maxNameSize
的值必须对其编译时用户可见
我做错了什么
您定义的数组变量的大小不是编译时常量
解决方案:你可以
- 在将变量用作数组大小的同一转换单元中定义变量,使其成为编译时常量。由于数组位于标头中,而标头可能包含在多个转换单元中,因此无法从外部定义大小。它必须是静态的或内联的李>
- 或者改用动态数组。创建动态数组的最简单方法是使用
李>std::vector
char device[configuration::maxNameSize];
char HTTPREQUESTS::device[configuration::maxNameSize];
// configuration.h
class configuration
{
public:
static const int maxNameSize = 30;
...
};
// configuration.h
namespace configuration
{
const int maxNamesize = 30;
...
}