C ++ console app:matrix(+ operator overloading error)

时间:2015-11-19 00:42:42

标签: c++ matrix operator-overloading

我目前正在实现矩阵类,我遇到了重载+运算符的问题。

具体实施如下:

**matrix.h:**

#pragma once
#include <iostream>
using namespace std;

template <typename t>
class Matrix
{
    int n, m;
    t **data;
public:
    Matrix(int, int, t);
    Matrix(Matrix &);
    ~Matrix();

    Matrix<t> operator+(const Matrix<t> &);
};

template<typename t> Matrix<t>::Matrix(int n = 1, int m = 1, t data = 0)
{
    this->n = n;
    this->m = m;
    this->data = new t*[this->n];

    for (int i = 0;i < n;++i)
    {
        this->data[i] = new t[this->m];
        for (int j = 0;j < m;++j)
        {
            this->data[i][j] = data;
        }
    }
}

template<typename t> Matrix<t>::Matrix(Matrix &m)
{
    this->n = m.n;
    this->m = m.m;
    this->data = new t*[this->n];

    for (int i = 0;i < n;++i)
    {
        this->data[i] = new t[this->m];
        for (int j = 0;j < this->m;++j)
        {
            this->data[i][j] = m.data[i][j];
        }
    }
}

template<typename t> Matrix<t>::~Matrix()
{
    for (int i = 0;i < this->n;++i)
        delete[] data[i];
    delete[] data;
}

template<typename t> Matrix<t> Matrix<t>::operator+(const Matrix<t> &x)
{
    if (x.n == n && x.m == m)
    {
        Matrix<t> temp(n, m, 0);
        for (int i = 0; i < n;++i)
            for (int j = 0; j < m;++j)
            {
                temp.data[i][j] = data[i][j] + x.data[i][j];
            }
        return temp;
    }
    else
    {
        return *this;
    }
}



**main.cpp:**

#include "matrix.h"

int main()
{
    Matrix<double> x(1, 1, 2); // defines a matrix 1x1 with all elements 2
    Matrix<double> y(1, 1, 3); // defines a matrix 1x1 with all elements 3
    Matrix<double> z(1, 1, 0); // defines a matrix 1x1 with all elements 0
    z=x+y;
}

当要执行+操作时,我收到运行时错误。这可能是什么问题?

0 个答案:

没有答案