在下面的代码中,我希望在调用 Class 构造函数时将数组定义为大小为 x 的数组。我该怎么做?
class Class
{
public:
int array[];
Class(int x) : ??? { }
}
最佳答案
你们太复杂了。当然,您可以在 C++ 中执行此操作。为了效率,他使用普通的阵列就可以了。一个 vector 只有在他不提前知道数组的最终大小时才有意义,即它需要随着时间的推移而增长。
如果您可以知道链中更高一级的数组大小,那么模板类是最简单的,因为没有动态分配,也没有内存泄漏的可能性:
template < int ARRAY_LEN > // you can even set to a default value here of C++'11
class MyClass
{
int array[ARRAY_LEN]; // Don't need to alloc or dealloc in structure! Works like you imagine!
}
// Then you set the length of each object where you declare the object, e.g.
MyClass<1024> instance; // But only works for constant values, i.e. known to compiler
如果你不知道你声明对象的地方的长度,或者你想重复使用不同长度的同一个对象,或者你必须接受一个未知的长度,那么你需要在你的构造函数中分配它并且在你的析构函数中释放它......(理论上总是检查以确保它工作......)
class MyClass
{
int *array;
MyClass(int len) { array = calloc(sizeof(int), len); assert(array); }
~MyClass() { free(array); array = NULL; } // DON'T FORGET TO FREE UP SPACE!
}
关于c++ - 在构造函数初始化程序中确定数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751878/