繁体   English   中英

具有多个数组的类的构造函数初始化器列表(C ++ 11可以,boost和std :: vector不可以)

[英]Constructor initilizer list for a class with multiple arrays (C++11 is ok, boost and std::vector are not)

我还不了解用于在构造函数初始化程序列表中初始化数组的新C ++ 11语法。 我不再受C ++ 03困扰,但由于程序限制,我无法使用boost或std :: vector。

FOO的实例必须通过构造函数调用确定大小,并且其行为就像静态已知x和y的大小一样。 新的C ++ 11功能是否允许这样做?

我不确定std::initializer_list<>可以或如何提供帮助。

class FOO
{
public:
    // this constructor needs to size x = count and y = count * 4
    FOO(int count) : 
    {
        // interate over x and y to give them their initial and permenent values
    }
private:
    const BAR x[];
    const TAR y[];
};

#include "foo.h"
void main(void)
{
    // both need to work as expected
    FOO alpha(30);
    FOO * bravo = new FOO(44);
}

您无法做您想做的事。 数组的大小必须是编译时常量。 尽管在您的特定用例中提供给构造函数的值可能是编译时常量,但C ++却不知道这一点。

此外,作为一种静态类型的语言,C ++要求能够在编译时计算类的大小。 sizeof(Foo)需要具有一个精确的单一值。 而你不能。

初始化程序列表不会帮助您。 您需要两个运行时大小的数组。 这就是std::vector目的。 如果要使用编译时大小的数组,则需要使用模板类型:

template<int count>
class FOO
{
public:
    FOO(initializer_list<Whatever> ilist)
    {
        // interate over x and y to give them their initial and permenent values
    }

private:
    const BAR x[count];
    const TAR y[count * 4];
};

#include "foo.h"
void main(void)
{
    // both need to work as expected
    FOO<30> alpha;
    FOO<44> * bravo = new FOO<44>;
}

除了Nicol Bolas使用模板参数使大小可编译时可配置的答案之外,您还可以在堆上分配内存:

class FOO
{
public:
    // this constructor needs to size x = count and y = count * 4
    FOO(int count) : x(new BAR[count]), y(new TAR[count])
    {
        // interate over x and y to give them their initial and permenent values
    }

    // Need a destructor to free the memory we allocated in the constructor
    ~FOO()
    {
        delete [] y;
        delete [] x;
    }
private:
    const BAR* x;
    const TAR* y;
};

暂无
暂无

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

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