在下面的代码中,我希望在调用 Class 构造函数时将数组定义为大小为 x 的数组。我怎样才能做到这一点?
class Class
{
public:
int array[];
Class(int x) : ??? { }
}
原文由 zaratustra 发布,翻译遵循 CC BY-SA 4.0 许可协议
在下面的代码中,我希望在调用 Class 构造函数时将数组定义为大小为 x 的数组。我怎样才能做到这一点?
class Class
{
public:
int array[];
Class(int x) : ??? { }
}
原文由 zaratustra 发布,翻译遵循 CC BY-SA 4.0 许可协议
就像已经建议的那样,对于大多数情况,向量是一个不错的选择。
或者,如果要避免动态内存分配并且在编译时已知最大大小,则可以将自定义分配器与 std::vector 一起使用,或者可以使用嵌入式模板库之类的库。
见这里: https ://www.etlcpp.com/home.html
示例类:
#include <etl/vector.h>
class TestDummyClass {
public:
TestDummyClass(size_t vectorSize) {
if(vectorSize < MAX_SIZE) {
testVector.resize(vectorSize);
}
}
private:
static constexpr uint8_t MAX_SIZE = 20;
etl::vector<int, MAX_SIZE> testVector;
uint8_t dummyMember = 0;
};
原文由 Spacefish 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
您不能使用在编译时无法计算的非常量维度来初始化数组的大小(至少在当前的 C++ 标准中,AFAIK 中没有)。
我建议使用
std::vector<int>
而不是数组。它为大多数操作提供了类似数组的语法。