构造函数中的动态内存分配

时间:2017-03-24 09:49:58

标签: c++ constructor destructor copy-constructor dynamic-memory-allocation

我正在学习动态内存分配。我有以下课程,其中A'应该在构造函数中拥有一个动态分配的数组。还应修改复制构造函数和析构函数。这就是我到目前为止......

#include <iostream>
#ifndef A_HH
#define A_HH

#include "B.hh"

class A {
public:

  A() {  B *array = new B[12];}
  A(const A&) { /* Do not know what to put here..*/ }
  ~A() { delete[] array;}

private:

   //B array[12] ; <- This is the array that I have to modify so it becomes dynamic. 
   B *array;
} ;

#endif 

2 个答案:

答案 0 :(得分:1)

对于初学者,你的默认构造函数用一个相同类型的局部变量覆盖成员变量“array”,所以你希望默认构造函数看起来像这样:

A() { array = new B[12]; }

然后复制构造函数可能需要深度复制数组,但是使用简单的数组,您无法在运行时告诉数组。您需要移动到更智能的容器(例如stl :: vector)或存储大小,但是一个天真的复制构造函数看起来像这样:

A(const A& other)
{
   array = new B[12];
   for(int i=0;i<12;i++)
   {
       array[i] = other.array[i];
   }
}

答案 1 :(得分:-1)

查看此代码:

#include <iostream>


using namespace std;

class MyArray{
public:
    int* array;
    int length;

    MyArray(int length){ // constructor which takes length of array as argument
        this->length = length;
        this->array = new int[this->length];

        for(int i=0; i<this->length; i++){
            this->array[i] = i;
        }
    }

    MyArray(const MyArray &obj){
        this->length = obj.length;
        this->array = new int[this->length];
        for(int i=0; i<this->length; i++)
        {
            this->array[i] = obj.array[i];
        }
    }

    ~MyArray(){ // destructor
        delete[] this->array;
    }


    void print(){ // test method for printing the array
    for(int i=0; i<this->length; i++){
            cout << this->array[i] << endl;
        }
        cout << endl;
    }

private:
protected:

};
int main()
{
    MyArray *array = new MyArray(10);
    MyArray *array2 = new MyArray(*array); // call copy constructor

    array->print();
    array2->print();

    delete array;
    delete array2;
}