【问题标题】:how to pass array to constructor in c++?如何将数组传递给C++中的构造函数?
【发布时间】:2014-11-05 05:18:39
【问题描述】:

我正在尝试将数组传递给 C++ 中的构造函数,但它不起作用:

arrayClass(int *array,int size){
        a = new int[15];
        for(int i(0); i < size; i++) {
           this->a[i] = array[i];
        }
        this->size = size;
cout << "In second constructor" << endl;
    }

在main()中

int array[3]={1,2,3};
arrayClass a2(array,3);

【问题讨论】:

  • 请让您的问题不那么含糊。 “不工作”可能意味着很多事情。你有错误吗?哪个?你能提供一个MCVE吗?
  • 你传入一个数组及其长度,但在构造函数中你将它复制到一个固定大小的数组(15),或者可能未初始化?如果athis-&gt;a是同一个数据,那就麻烦了。

标签: c++ arrays constructor


【解决方案1】:

您的示例运行良好 - 只需在完成后注意 delete[]new[] 分配空间(以防止内存泄漏)。此外,您可能希望使用参数size,而不是使用 15 作为硬编码常量(否则对于大于 15 个元素的数组,您会遇到内存访问冲突)。

class ArrayClass{
public:
  ArrayClass(int* array, int size){
    a = new int[size];
    for (int i(0); i < size; i++) {
      this->a[i] = array[i];
    }
    this->size = size;
  }
  virtual ~ArrayClass(){
    delete[] a;
  }
private:
  int* a;
  int size;
};

int main(int argc, char** argv){
  int array[3] = { 1, 2, 3 };
  ArrayClass a2(array, 3);
  return 0;
}

在 C++ 中可以通过不同的方式分配数组:

int a[3]; // will allocate the space for 3 elements statically from the stack

int* a = new int[3]; // will allocate space for 3 elements dynamically from the heap

基本上,它决定了您的数组将位于哪个内存中-但这两种方法存在许多差异-请参阅What and where are the stack and heap?。 一些主要区别是:

  • 堆栈分配不能像变量一样使用动态长度,即int size = 10; int a[size]; // &lt;- is invalid
  • 堆栈分配在超出范围时会被自动“删除”
  • 堆分配必须是 deleted[] 显式才能不泄漏内存

int* a = new int[3]; 行将声明一个指针变量指向可以容纳 3 个 int 值的内存位置。因此,在声明之后,这 3 个值可以直接寻址为 a[0]a[1] 和 @987654333 @。完成所有操作后,delete[] a; 是必要的。因为如果指针 a* 超出范围(即函数结束),则不会自动释放 3 个值的内存。

【讨论】:

  • Constantin: 非常感谢。但我有疑问你能解释一下 int a 与 int a 之间的区别。int* 代表指针数组吗?
  • @user2895589 我已经编辑了我的答案并更详细地解释了int* a = new int[size];。希望对你有帮助!
猜你喜欢
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多