c++ - 在构造函数初始化程序中确定数组大小

标签 c++ arrays constructor initialization

在下面的代码中,我希望在调用 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/

相关文章:

c++ - C++程序中的内存泄漏

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

c++ - 为什么 vector 不循环更新?

c++ - 字符串编码问题?

java - 为什么会抛出java.lang.InstantiationException?

actionscript-3 - ActionScript 3 构造函数参数问题

c++ - 动态分配的类对象

ios - 据说通过编辑副本将被污染的 NSArray 分开

带有 byte[] 参数的 NHibernate ISQLQuery 抛出错误

C++:通过数组创建的对象,但如何传递参数?