【问题标题】:Implement 2D matrix from classes C++从 C++ 类实现二维矩阵
【发布时间】:2015-05-16 20:28:15
【问题描述】:

我是 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;
}

【问题讨论】:

标签: c++ oop matrix multidimensional-array


【解决方案1】:

你的线路

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

错了。简单使用

Matrix object(d1,d2);

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

【讨论】:

  • 我尝试使用在线 IDE 编译它,但收到此错误Segmentation fault (core dumped) code: goo.gl/Nixxen
  • @Capser 第一步是让它编译。段错误通常来自错误的分配/越界访问。尝试调试您的代码并确保您的指针有效并且您正在为它们分配内存。特别是在构造函数中,你应该首先调用allocArray()(想想参数mn,基本上你必须通过你的构造函数来设置它们),并且只有在初始化p之后。您现在正在反向执行此操作,因此您首先写入不属于您的内存,并且仅在分配内存之后。
  • 我已经修复了,错误消失了但是没有输出
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2021-08-14
    • 2016-03-10
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多