# 从类C ++实现2D矩阵Implement 2D matrix from classes C++

*更新：我已经修复了一些代码，但是矩阵不打印任何内容

``````#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 个回复2

### ===============>>#1 票数：2 已采纳

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

``````Matrix object(d1,d2);
``````

## 未解决问题？本站智能推荐：

1回复

2回复

3回复

3回复

2回复

2回复

1回复

4回复

2回复

### 函数中两个矩阵的误差总和使用二维数组

================================================== ==============================您看到我要在其中使用2d数组添加2个矩阵的程序，而我我还使用函数add(int x[3][3], int y[3][3],int z
2回复