0

我正在制作一类矩阵并试图通过创建一个新的二维矩阵来显示。当我编译并运行这段代码时,程序就退出了,屏幕上什么也没有出现。我无法理解这个问题。任何帮助将不胜感激。谢谢

#include <iostream>
using namespace std;

//making a class of matrix
class Matrix{
private:
    int **array;
    int row,col;
public:
    void initialize(int r,int c);  //function to initialize the array
    //dynamically
    Matrix(int r,int c);           //this function initializes a matrix of r
    //rows and c columns
    ~Matrix();                    //delete the matrix by this
    void display_matrix();         //display matrix
    int get_rows();                //get rows of matrix
    int get_columns();             //get columns of matrix
};

//function to initialize the matrix
void Matrix::initialize(int r,int c)
{
    r=row;
    c=col;

    array=new int*[r];         //creating a 1D array dynamically
    for (int i=0;i<r;i++)
    {
        array[i]=new int[c];      //making the array 2D by adding columns to it
    }

    for (int i=0;i<r;i++)
    {
        for (int j=0;j<c;j++)
        {
            array[i][j]=0;        //setting all elements of array to null
        }
    }
}

//initializing NULL matrix
Matrix::Matrix()
{
    initialize(0,0);
}

//setting row aand columns in matrix
Matrix::Matrix(int r,int c)
{
    initialize(r,c);   //function used to initialize the array
}

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

int Matrix::get_rows()
{
    return row;        //return no. of rows
}

int Matrix::get_columns()
{
    return col;      //return columns
}

//display function
void Matrix::display_matrix()
{
    int c=get_columns();
    int r=get_rows();
    for (int i=0;i<r;i++)
    {
        for (int j=0;j<c;j++)
        {
            cout<<array[i][j]<<" ";      //double loop to display all the elements of
            //array
        }
        cout<<endl;
    }
}

int main()
{
    Matrix *array2D=new Matrix(11,10);   //making a new 2D matrix
    array2D->display_matrix();   //displaying it
    system("PAUSE");
    return 0;
}
4

2 回答 2

3

难道不应该

void Matrix::initialize(int r,int c)
 {
 r=row;   //Shouldn't it be row = r;
 c=col;   //Shouldn't it be col = c;
...
}
于 2012-11-28T09:28:28.763 回答
3

您的错误在initialize

void Matrix::initialize(int r,int c)
{
    r=row;
    c=col;

    ...

您正在将函数变量 'r' 和 'c' 设置为类变量 'row' 和 'col' 具有的任何值。我很确定你打算做相反的事情。

您还确定这是您编译的实际代码吗?你的班级缺少一个声明Matrix()

于 2012-11-28T09:30:32.733 回答