Перегрузка матрицы C ++

0

В заголовочном файле я могу добавить объявление функций, которые мне нужны для перегрузки операторов. Затем выполните функции, которые я добавил в файл заголовка.

Может ли кто-нибудь помочь мне с тем, что я должен делать? Пожалуйста, объясните, чтобы я мог повернуть голову вокруг перегрузки, если это возможно.

Я перечислил приведенный ниже код. Что касается основного, я не должен его редактировать.

Файл заголовка Matrix.h

#ifndef MATRIX_H
#define MATRIX_H

class Matrix
{
  public:
    Matrix (int sizeX, int sizeY);
    ~Matrix();
    int GetSizeX() const { return dx; }
    int GetSizeY() const { return dy; }
    long &Element(int x, int y);        // return reference to an element
    void Print () const;

  private:
    long **p;       // pointer to a pointer to a long integer
    int dx, dy;
};

#endif  /* MATRIX_H */

Файл Matrix.cpp

#include <iostream>
#include <cassert>
#include "Matrix.h"

using namespace std;

Matrix::Matrix (int sizeX, int sizeY) : dx(sizeX), dy(sizeY)
{
    assert(sizeX > 0 && sizeY > 0);
    p = new long*[dx];      
                // create array of pointers to long integers
    assert(p != 0);
    for (int i = 0; i < dx; i++)
    {     // for each pointer, create array of long integers
        p[i] = new long[dy];  
        assert(p[i] != 0);
        for (int j = 0; j < dy; j++)
            p[i][j] = 0;
    }
}

Matrix::~Matrix()
{
    for (int i = 0; i < dx; i++)
        delete [] p[i]; // delete arrays of long integers
    delete [] p;    // delete array of pointers to long
}

long &Matrix::Element(int x, int y)
{
    assert(x >= 0 && x < dx && y >= 0 && y < dy);
    return p[x][y];
}

void Matrix::Print () const
{
    cout << endl;
    for (int x = 0; x < dx; x++)
    {
        for (int y = 0; y < dy; y++)
            cout << p[x][y] << "\t";
        cout << endl;
    }
}

main.cpp

#include <cstdlib>
#include <iostream>
#include <cassert>
#include <ctime>
#include "Matrix.h"

using namespace std;

int main(int argc, char** argv) {
    int size1, size2, size3;
    const int RANGE = 5; //using to generate random number in the range[1,6]

    cout << "Please input three positive integers: (size)";
    cin >> size1 >> size2 >> size3;
    assert(size1 > 0 && size2 > 0 && size3 > 0);

    Matrix myMatrix1(size1, size2), myMatrix2(size2,size3);
    Matrix yourMatrix1(size1, size2), yourMatrix2(size2, size3);
    Matrix theirMatrix1(size1, size2), theirMatrix2(size1, size3);

    srand(time(0));
    for (int i = 0; i < size1; i++)
        for (int j = 0; j < size2; j++)
            myMatrix1(i,j) = rand() % RANGE + 1;
    yourMatrix1 = 2 * myMatrix1;
    theirMatrix1 = myMatrix1 + yourMatrix1;
    cout << "myMatrix1: " << endl;
    cout << myMatrix1 << endl << endl;

    cout << "yourMatrix1 = 2 * myMatrix " << endl;
    cout << yourMatrix1 << endl << endl;

    cout << "myMatrix1 + yourMatrix1: " << endl;
    cout << theirMatrix1 << endl << endl;

    for (int i = 0; i < size2; i++)
        for (int j = 0; j < size3; j++)
            myMatrix2(i,j) = rand() % RANGE + 1;
    yourMatrix2 = myMatrix2 * 3;
    theirMatrix2 = myMatrix1 * yourMatrix2;
    cout << "myMatrix1: " << endl;
    cout << myMatrix1 << endl << endl;

    cout << "myMatrix2: " << endl;
    cout << myMatrix2 << endl << endl;

    cout << "yourMatrix2 = myMatrix2 * 3 " << endl;
    cout << yourMatrix2 << endl << endl;

    cout << "myMatrix1 * yourMatrix2: " << endl;
    cout << theirMatrix2 << endl << endl;

    return 0;
}
Теги:
matrix
operator-overloading
overloading
function-overloading

1 ответ

0

Вам нужно заглянуть в главное и посмотреть, что все операторы используются с объектами Matrix. Вы должны перегрузить эти операторы в класс Matrix указанный вами, т.е. записывать функции-члены в этот класс.

Для получения подробной информации о перегрузке оператора см. Следующую ссылку:

http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading

  • 0
    Я добавил main.cpp к своему вопросу. Я считаю, что мне нужны два оператора + и *.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню