[英]Constructor initilizer list for a class with multiple arrays (C++11 is ok, boost and std::vector are not)
I don't understand the new C++11 syntax yet for initializing an array in a constructor initilizer list. 我还不了解用于在构造函数初始化程序列表中初始化数组的新C ++ 11语法。 I'm no longer stuck with C++03 but I can't use boost or std::vector because of program constraints. 我不再受C ++ 03困扰,但由于程序限制,我无法使用boost或std :: vector。
An instance of FOO must be sized by the constructor call and behave as though the sizes of x and y were statically known. FOO的实例必须通过构造函数调用确定大小,并且其行为就像静态已知x和y的大小一样。 Does the new C++11 features allow this? 新的C ++ 11功能是否允许这样做?
I'm not sure if or how std::initializer_list<>
can help. 我不确定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);
}
You can't do what you're trying to do. 您无法做您想做的事。 The sizes of arrays must be compile-time constants. 数组的大小必须是编译时常量。 And while the values provided to the constructors in your particular use cases may be compile-time constants, C++ can't know that. 尽管在您的特定用例中提供给构造函数的值可能是编译时常量,但C ++却不知道这一点。
Furthermore, as a statically-typed language, C++ requires being able to compute the size of the class at compile-time. 此外,作为一种静态类型的语言,C ++要求能够在编译时计算类的大小。 sizeof(Foo)
needs to have an exact, single value. sizeof(Foo)
需要具有一个精确的单一值。 And your's can't. 而你不能。
Initializer lists aren't going to help you. 初始化程序列表不会帮助您。 You want two runtime-sized arrays; 您需要两个运行时大小的数组。 that's what std::vector
is for. 这就是std::vector
目的。 If you want compile-time sized arrays, you need to use a template type: 如果要使用编译时大小的数组,则需要使用模板类型:
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>;
}
Besides the answer from Nicol Bolas using template parameters to make the size compile-time configurable, you can also allocate memory on the heap: 除了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.