在 C++ 中初始化动态二维数组

Initializing Dynamic 2d array in c++

我已经创建了 class 和第一个构造函数,但我不知道如何按照 2 中的要求将 2d 数组初始化为 ref,需要使用动态内存分配来完成此操作。

创建一个 class 命名矩阵,其中包含私有成员:

• int **p;

• 整数行;

• 整数列;

class应该有以下成员函数:

  1. matrix() 将二维数组初始化为零。假设 rows = 2 和 cols = 2
  2. matrix(int **ref, int r, int c) 将二维数组初始化为ref

我的代码:


class Matrix
{
    private:
        int **p;
        int rows;
        int cols;
    public:
        // CONSTRUCTORS
        Matrix()
        {
            rows = 2;
            cols = 2;
            p = new int*[2];
            // initialize the array with 2x2 size
            for (int i=0; i<2; i++)
            {
                p[i] = new int[2];
            }
            //  taking input for the array
            for (int i=0; i<2; i++)
            {
                for (int j=0; j<2; j++)
                {   
                    p[i][j] = 0;
                }
            }


        }; 
        
        Matrix(int **ref, int r, int c)
        {
            rows = r;
            cols = c;
            p = new int*[rows];
            // initialize the array with 2x2 size
            for (int i=0; i<rows; i++)
            {
                p[i] = new int[cols];
            }
            //  taking input for the array
            for (int i=0; i<rows; i++)
            {
                for (int j=0; j<cols; j++)
                {   
                    p[i][j] = **ref;
                }
            }
        }

        friend ostream& operator << (ostream& output, Matrix& obj)
        {
            output << obj.rows;
            cout << " = ROWS" << endl;
            output << obj.cols;
            cout << " = columns" << endl;
            for (int i=0; i<obj.rows; i++)
            {
                for(int j=0; j<obj.cols;j++)
                {
                    cout << obj.p[i][j] << " " ;
                }
                cout << endl;
            }
            return output;
        }
};

int main()
{
    Matrix a;
    cout << a << endl;
    return 0;
}

好像p[i][j] = **ref;应该是p[i][j] = ref[i][j];.

你也应该关注The Rule of Three。换句话说,您应该声明复制构造函数和赋值运算符以正确处理对象(包括指针)复制。