【问题标题】:Copy constructor for 2d array c++二维数组c ++的复制构造函数
【发布时间】:2023-04-08 13:33:01
【问题描述】:

我已经设法重载了赋值运算符,所以我确实有一个解决方法,但很高兴知道为什么我不能让它工作。

我的 arr2d 类的开头如下所示:

template <class type> class arr2d {

private:
    type* m_ptr;
    int m_nx,m_ny;

public:
    arr2d(){
            m_ptr = 0;
            m_nx = 0;
            m_ny = 0;
    }
    // Default constructor creates a null array

    arr2d(int nx, int ny):m_nx(nx),m_ny(ny){
            m_ptr = new type [nx*ny];
            if ( m_ptr==0 ){cout << "\nError allocating heap memory.\n";}
    }

//      // Copy constructor
//      arr2d(const arr2d& rhs){
//              m_ptr = new type [m_nx*m_ny];
//              for(int j=0;j<m_ny;j++){
//              for(int i=0;i<m_nx;i++){
//                     m_ptr[j*m_nx+i] = rhs.m_ptr[j*m_nx+i];
//              }
//              }
//       }

等等,

你可以看到我尝试的复制构造函数被注释掉了。

现在在我的主目录中,我想调用复制构造函数,例如:

arr2d b=a;

b 数组现在与 a 具有相同的值。我做错了什么?

【问题讨论】:

标签: c++ arrays pointers constructor copy


【解决方案1】:

您的复制构造函数没有分配数组大小。应该是这样的

arr2d(const arr2d& rhs) : m_nx(rhs.m_nx), m_ny(rhs.m_ny) {
    ...
}

【讨论】:

    【解决方案2】:

    除了像6502说的那样初始化m_nxm_ny之外,在声明b的时候还需要模板参数。例如

    arr2d<int> b = a;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-13
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 2022-01-08
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多