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

标签 c++ arrays dynamic 2d

我已经创建了类和第一个构造函数,但是我不知道如何按照 2 中的要求将 2d 数组初始化为 ref,需要使用动态内存分配来执行此操作。
创建一个名为 matrix 的类,具有跟随的私有(private)成员:
• int **p;
• int 行;
• 整数列;
该类应具有以下成员函数:

  • matrix () 将二维数组初始化为零。假设行 = 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 .换句话说,您应该声明复制构造函数和赋值运算符以正确处理对象(包括指针)复制。

    关于c++ - 在 C++ 中初始化动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62819066/

    相关文章:

    c++ - 全局声明类对象但不带参数

    c++ - 编译后停止和仅检查语法之间的区别

    c++ - 更改 const 对象的数组成员的元素

    c++ - 如何有效地将数字字符串值分配给整数?

    javascript - 我如何优化 es6 中的 .concat 方法

    arrays - 使用唯一 id 列减去 2 维数组

    linq - 动态 LINQ 和动态 Lambda 表达式?

    java - Android 以编程方式添加 View 重复索引

    angular - 如何更新 Angular 中提供者提供的值?

    C++我如何为switch case做异常处理