警告"ISO C ++禁止使用可变大小的数组".具有恒定大小的数组 [英] Warning "ISO C++ forbids variable-size array" with constant size array

查看:69
本文介绍了警告"ISO C ++禁止使用可变大小的数组".具有恒定大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c ++程序,其中常量存储在一个类中.在代码的其他地方,我将这些常量之一用作数组大小.

I have a c++ program in which constants are stored within a class. And somewhere else in the code I use one of these constants as an array size.

以下是示例:

Constants.h

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:
    static const unsigned int C_BufferSize;
};

#endif

Constants.cpp

#include "Constants.h"

const unsigned int Constants::C_BufferSize(128);

main.cpp

#include "Constants.h"

int main()
{
    char buffer[Constants::C_BufferSize];
    return 0;
}


当我使用 -std = c ++ 11 -pedantic 编译此代码时,收到以下警告:


When I compile this code with -std=c++11 -pedantic I got the following warning:

main.cpp:5:37:警告:ISO C ++禁止使用可变长度数组缓冲区" [-Wvla]

main.cpp:5:37: warning: ISO C++ forbids variable length array ‘buffer’ [-Wvla]

由于大小是一个常数,我不太理解错误,我猜是在编译时大小未知.

I don't really understand the error since the size is a constant, my guess is that at compile time the size is unknown.

可以使用堆分配表(与new分配)绕过错误,但是我禁止使用动态内存分配.因此,我正在寻找另一种解决方案.

The error can be bypassed using a heap allocated table (allocated with new), but I'm forbidden to use dynamic memory allocation. Therefore I'm looking for another solution.

推荐答案

定义是必需的,并且在链接时进行搜索.是的,在编译阶段大小是未知的.

The definition is required and searched for, at link-time. So yes, the size is unknown during the compilation phase.

您是这样写的:

class Constants
{
public:
    static const unsigned int C_BufferSize = 128; //initialize here
};

,然后仅在 .cpp 文件中提供定义:

And then only provide the definition in .cpp file:

const unsigned int Constants::C_BufferSize; //no initialization here


但是,最好使 Constants 为命名空间而不是类:

namespace Constants  //NOTE : a namespace now
{
    static const unsigned int BufferSize = 128; 
};

对我来说似乎更自然.

这篇关于警告"ISO C ++禁止使用可变大小的数组".具有恒定大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆