繁体   English   中英

在 class 中声明 static 数组,并将大小传递给构造函数?

[英]Declare static array in class with size passed to constructor?

有什么办法可以在 class 中声明 static 数组,其大小已传递给构造函数? 如果大小必须是 const 也没关系,这使得无法在运行时设置它。

我试着做这样的事情:

class class_name
{
    public:
        float* map;
        class_name(int n, const int d)
        {
            float arr[d];
            map = arr;
        }
};

但我觉得这可能是个非常糟糕的主意。 不好吗? 如果是,那又是为什么呢?

是的,这段代码

    class_name(int n, const int d)
    {
        float arr[d];
        map = arr;
    }

是个坏主意,有两个原因

  1. float arr[d]; 在堆栈中创建一个局部变量,因此它在块的末尾不再存在。 所以map变成了悬空指针。 如果您需要动态大小分配,您应该只使用std::vector<float> map并避免很多麻烦。
  2. float arr[d]; 是变长数组,C++不支持那些。 使d成为const没有帮助,它必须是一个实际常量,而不是const变量。

解决方案:既然你说数组长度可以在编译时确定,这非常适合模板:

template <std::size_t N>
class class_name
{
    public:
        std::array<float, N> map { {} }; // { {} } causes value initialization of everything to 0
        // actually above could be `float map[N];` but it has the C array gotchas
        
        class_name(int n)
        {
            // not sure what n is for...
        }
};

并声明这个 class 的变量:

class_name<5> obj; // obj.map size is 5

“静态数组”是指大小不变的东西吗? std::unique_ptr<float[]>std::make_unique(std::size_t)可能是一个选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM