矩阵元素(使用类)未显示c ++

时间:2012-11-28 09:25:20

标签: c++

我正在创建一个矩阵类并尝试通过创建一个新的2D矩阵进行显示。当我编译并运行此代码时,程序只是退出并且屏幕上没有任何内容。 我无法理解这个问题。任何帮助都会受到赞赏。谢谢。

#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;
}

2 个答案:

答案 0 :(得分:3)

不应该是

void Matrix::initialize(int r,int c)
 {
 r=row;   //Shouldn't it be row = r;
 c=col;   //Shouldn't it be col = c;
...
}

答案 1 :(得分:3)

您的错误位于initialize

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

    ...

您正在将函数变量'r'和'c'设置为类变量'row'和'col'所具有的值。我很确定你的意思是反其道而行。

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

的声明