Перегрузка оператора + динамическая матрица - PullRequest
0 голосов
/ 07 февраля 2019

Итак, я решил перезапустить мою программу все, кроме оператора + сейчас работает.Я получаю исключение нарушения прав чтения

Заголовочный файл

#pragma once
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

class MatrixType
{
private:
    int **matrix;
    int row;
    int col;
public:
    void setElement(int r, int c, int newvalue);
    void display();

    const MatrixType& operator=(const MatrixType& mat);
    MatrixType operator+(const MatrixType& mat) const;

    friend std::ostream & operator << (std::ostream & out, const MatrixType & mat);

    MatrixType(int r, int c);
    MatrixType(string fileName);
    MatrixType(const MatrixType& mat);
    MatrixType();
    ~MatrixType();
};

Файл реализации

#include "matrixType.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

void MatrixType::setElement(int r, int c, int newvalue)
{
    matrix[r][c] = newvalue;
}

void MatrixType::display()
{
    for (int i = 0; i < row; i++)
    {
        for (int r = 0; r < col; r++)
            cout << matrix[i][r] << " ";
        cout << endl;
    }
    cout << endl;
}

const MatrixType& MatrixType::operator=(const MatrixType& mat)
{
    if (row != mat.row)
    {
        cout << "The matrixes are not identical" << endl;
        return *this;
    }
    for (int i = 0; i < row; i++)
    {
        for (int r = 0; r < col; r++)
        {
            matrix[i][r] = mat.matrix[i][r];
        }
    }
    return *this;
}

MatrixType MatrixType::operator+(const MatrixType& mat) const
{
    MatrixType tempMatrix;
    if (row != mat.row)
    {
        cout << "The matrixes are not identical can not be added together" << endl;
        return *this;
    }
    else
    {
        for (int i = 0; i < mat.row; i++)
        {
            for (int r = 0; r < mat.col; r++)
            {
                tempMatrix.matrix[i][r] = mat.matrix[i][r] + matrix[i][r];
            }
        }
        return tempMatrix;
    }
}

std::ostream & operator << (std::ostream & out, const MatrixType & mat)
{
    for (int i = 0; i < mat.row; i++) {
        for (int j = 0; j < mat.col; j++) {
            out << mat.matrix[i][j] << "  ";
        }
        out << std::endl;
    }
    return out;
}

MatrixType::MatrixType(int r, int c)
{
    matrix = new int*[r];
    for (int i = 0; i < r; i++)
    {
        matrix[i] = new int[c];
    }
    row = r;  
    col = c;
    for (int i = 0; i < row; i++)
    {
        for (int s = 0; s < col; s++)
        {
            matrix[i][s] = 0;
        }
    }
}
MatrixType::MatrixType(string fileName)
{
    int r;
    int c;
    int z;
    ifstream myFile;
    myFile.open(fileName);
    myFile >> r;
    myFile >> c;
    matrix = new int*[r];
    for (int i = 0; i < r; i++)
    {
        matrix[i] = new int[c];
    }

    for (int i = 0; i < r; i++)
    {
        for (int s = 0; s < c; s++)
        {
            myFile >> z;
            matrix[i][s] = z;
        }
    }
    row = r;
    col = c;
    myFile.close();
}

MatrixType::MatrixType(const MatrixType& mat)
{
    row = mat.row;
    col = mat.col;
    matrix = new int*[row];
    for (int i = 0; i < row; i++)
    {
        matrix[i] = new int[col];
    }
    for (int i = 0; i < row; i++)
    {
        for (int s = 0; s < col; s++)
        {
            matrix[i][s] = mat.matrix[i][s];
        }
    }
}

MatrixType::MatrixType()
{
}

MatrixType::~MatrixType()
{
    for (int i = 0; i < row; i++)
    {
        delete[] matrix[i];
    }
    delete[] matrix;
}

Исходный код

#include "MatrixType.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    MatrixType M1("matrixfile1.txt");
    MatrixType M2("matrixfile2.txt");
    MatrixType M3("matrixfile3.txt");

    cout << "Matrix 1:" << endl << M1 << endl << endl;
    cout << "Matrix 2:" << endl << M2 << endl << endl;
    cout << "Matrix 3:" << endl << M3 << endl << endl;

    MatrixType M4 = M1 + M3;

    return 0;
}

Таким образом, в основном цель состоит в том, чтобы проверить, идентичны ли матрицы, в противном случае вы должны просто увидеть отпечаток, матрицы которого не одинакового размера.Матричный файл1,2,3, который выглядит как

3 3

1 1 1

1 1 1

1 1 1

Это показывает размеры массива и их элементов.Мой вопрос заключается в том, что я мог бы сделать, чтобы моя операторская функция работала лучше, поскольку в настоящее время она еще не может складывать матрицы вместе.Все остальное, хотя и снова работает, это просто оператор, который получает нарушение прав на чтение.

1 Ответ

0 голосов
/ 07 февраля 2019
MatrixType::MatrixType()
{
}

Это не инициализирует элементы row, col или matrix вообще, поэтому нереально пытаться использовать текущие значения любого из них.

Так как вы вообще не предоставили способ изменить размеры MatrixType, даже используя operator=, кажется, что нет никакого хорошего использования конструктора по умолчанию, и, вероятно, конструктор MatrixType() по умолчанию долженне существует вообще.

MatrixType MatrixType::operator+(const MatrixType& mat) const
{
    MatrixType tempMatrix;

Ваш operator+ начинается с инициализации tempMatrix с использованием конструктора по умолчанию.Таким образом, размеры tempMatrix равны ...?

...