c++ - 从 C++ 类实现二维矩阵

标签 c++ oop matrix multidimensional-array

我是 C++ 的新手,目前我正在尝试从类中实现 2D 矩阵,这是我当前的代码,现在我无法创建矩阵对象的实例,请给我反馈我需要什么修理。

*更新:我已经修复了一些代码,但是矩阵没有打印任何东西

#include <iostream>
#include <cstdlib>
using namespace std;

class Matrix
{
    public:
        Matrix(); //Default constructor
        Matrix(int *row, int *col); //Main constructor
        void setVal(int row, int col, int val); //Method to set the val of [i,j]th-entry
        void printMatrix(); //Method to display the matrix
        ~Matrix(); //Destructor

    private:
        int row, col;
        double **matrix; 

        //allocate the array
        void allocArray()
        {
            matrix = new double *[*row];
            for (int count = 0; count < *row; count++)
                *(matrix + count) = new double[*col];
        }
};

//Default constructor
Matrix::Matrix() : Matrix(0,0) {}

//Main construcor
Matrix::Matrix(int *row, int *col)
{   
    allocArray();
    for (int i=0; i < *row; i++)
    {
        for (int j=0; j < *col; j++)
        {
            *(*(matrix + i) + j) = 0;
        }
    }
}

//destructor
Matrix::~Matrix()
{
    for( int i = 0 ; i < row ; i++ )
        delete [] *(matrix + i) ;
    delete [] matrix;
}

//SetVal function
void Matrix::setVal(int row, int col, int val)
{
    matrix[row][col] = val;
}

//printMatrix function
void Matrix::printMatrix()
{
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < col; j++)
            cout << *(*(matrix + i) + j) << "\t";
        cout << endl;
    }
}


int main()
{
    int d1 = 2;
    int d2 = 2;

    //create 4x3 dynamic 2d array
    Matrix object(&d1,&d2);

    object.printMatrix();

    return 0;
}

最佳答案

你的线路

Matrix object = new int **Matrix(d1,d2);

错了。简单使用

Matrix object(d1,d2);

不需要类似 Java 的语法,实际上在 C++ 中这意味着动态分配:Matrix* object = new Matrix(d1,d2);

关于c++ - 从 C++ 类实现二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30280414/

相关文章:

c++ - STL map<string, string>,给key赋0值导致编译错误

c++ - 如何在 Code::Blocks 上启用 SSE/SSE2?

Haskell 线性代数?

swift - 一个服务应该调用另一个服务还是应该获取它自己的数据

python - 为什么在 python 中使用 dual __init__?

c - 如何创建这个矩阵? C

r - 根据向量给出的 ID 从矩阵中提取多行

c++按值或指向函数语法的指针传递数组

c++ - 具有 void 函数的模板特化

python - python 中的属性错误。对象没有属性