如何初始化一个给定长度作为对象参数的成员数组



我无法通过传递给对象的参数来确定成员数组的大小。

现在我有这样的东西,即使不是很方便,它也能工作:成员数组的大小直接在类头中定义

main.cpp:

int main()
{
Test foo;
}

class_test.cpp:

Test::Test()
{
}

class_test.h:

class Test
{
public:
Test();
private:
std::array<int,10> myarray; // I define the size here. 
};

现在我想在创建对象时将数组大小作为参数传递。类似以下内容:

main.cpp:

int main()
{
Test foo(10); // I pass the array size
}

class_test.cpp:

Test::Test(int size): arraysize(size) // I affect the size to a class attribute
{
}

class_test.h:

class Test
{
public:
Test(int size);
private:
int arraysize;
std::array<int,arraysize> myarray; // I use the attribute to determine the member array size
};

我尝试了很多解决方案,但最终总是出现编译错误。我看到了关于这个主题的其他线程,但它们不允许我找到如何处理这个配置。

我可以使用向量,但在我的情况下,数组的额外性能是非常有益的。

在编译时必须知道数组的大小(换句话说,它是常量(。

要么使用std::vector,要么在类型中烘焙该尺寸:

template<int N> // make it a template parameter
class Test
{
public:
Test() {}
private:
std::array<int, N> myarray;
};
Test<10> test; // array of 10 elements.

就我个人而言,我推荐矢量,因为我怀疑性能差异有那么大。

最新更新