![](/img/trans.png)
[英]C++11 std::vector of template class with argument in constructor
[英]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.