从类C ++实现2D矩阵

时间:2015-05-16 20:28:16

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

你的行

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

错了。简单地使用

Matrix object(d1,d2);

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

答案 1 :(得分:1)

而不是Matrix object = new int **Matrix(d1,d2);使用Matrix* object = new Matrix(d1,d2); 此外,您必须使用object->printMatrix();代替object.printMatrix();