我还不了解用于在构造函数initilizer列表中初始化数组的新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);
}
答案 0 :(得分:3)
你无法做你想做的事。数组的大小必须是编译时常量。虽然在特定用例中提供给构造函数的值可能是编译时常量,但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>;
}
答案 1 :(得分:0)
除了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;
};