具有恒定大小数组的警告"ISO C++ forbids variable-size array"
Warning "ISO C++ forbids variable-size array" with constant size array
我有一个c++程序,其中常量存储在类中。在代码中的其他地方,我使用这些常量之一作为数组大小。
下面是一个示例:
常量.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class Constants
{
public:
static const unsigned int C_BufferSize;
};
#endif
常量.cpp
#include "Constants.h"
const unsigned int Constants::C_BufferSize(128);
主.cpp
#include "Constants.h"
int main()
{
char buffer[Constants::C_BufferSize];
return 0;
}
当我用-std=c++11 -pedantic
编译此代码时,我收到以下警告:
main.cpp:5:37: 警告:ISO C++禁止可变长度数组"缓冲区" [-WVLA]
我真的不明白这个错误,因为大小是一个常量,我的猜测是在编译时大小是未知的。
可以使用堆分配表(使用 new 分配)绕过该错误,但我被禁止使用动态内存分配。因此,我正在寻找另一种解决方案。
定义是必需的,并且在链接时进行搜索。所以是的,在编译阶段大小是未知的。
你写的是这个:
class Constants
{
public:
static const unsigned int C_BufferSize = 128; //initialize here
};
然后只在.cpp
文件中提供定义:
const unsigned int Constants::C_BufferSize; //no initialization here
但是,将Constants
作为命名空间而不是类更有意义:
namespace Constants //NOTE : a namespace now
{
static const unsigned int BufferSize = 128;
};
对我来说似乎更自然。
警告原因 - 正如@nawaz已经提到的(编译时数组中的变量大小 - 可能不是所有编译器都支持/允许)。
可以通过以下方式尝试:
std::vector<char> buffer(Constants::C_BufferSize);
通常,在执行一些char*
转换为string
时会出现上述问题(受字符缓冲区中的实际数据大小限制)。因此,在这种情况下,可以使用类似的东西;
std::string ConvertCharDataBySizeToString(const char* s, std::size_t size)
{
std::vector<char> data(s, s+size);
return ( std::string(data.begin(), data.end()) );
}
参考资料在这里。
相关文章:
- 如何使用 C++将 ISO-2022-KR 编码转换为 UTF-8 编码?
- ISO C++禁止声明没有类型的"setInputNombre"
- ISO C++禁止指针和整数 [-fpermissive] [c++] 之间的比较
- 为什么我会收到此警告:ISO c++ 禁止可变长度数组"v"[-Wvla]
- ISO 中禁止可变长度数组 C++崇高文本中的错误 3.
- 是否存在经过认证(ISO 26262或类似)C++标准库?
- 张量流错误 此文件需要编译器和库支持 ISO C++ 2011 标准
- 错误:ISO C++禁止可变长度数组"subVec"[-Werror=vla]
- Clang-CL 警告 strnicmp 已弃用,请使用 ISO C 并C++符合标准的名称_strnicmp
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- DEV C++ 第 69 行 [错误] ISO "for" 范围更改了"i"的名称查找 [-允许]
- 错误:ISO C++禁止在指针和整数 [-fallowive] 之间进行比较
- 警告:ISO C++禁止可变长度数组
- 包括C++标题,"..."与<...>风格,ISO / IEC官方意见?
- 在 c++ 中将 ISO 日期时间转换为本地日期时间并提取时间
- 在 Boost 中解析 RFC3339/ISO 8601 时间戳
- :<command-line>0:3:警告:ISO C++11 要求宏名称后有空格
- C++错误:ISO C++禁止声明.没有类型
- 警告:ISO C++禁止将字符串常量转换为'char*' [-Wwrite-strings]
- 将 OR 放入 if 语句会导致 ISO C++禁止指针和整数之间的比较(f 允许)