简体   繁体   English

重载运算符:矩阵加法

[英]Overloading operator: Matrix Addition

enter image description here 在此处输入图片说明

I'm trying to set up my functions and perform some overloading operations so that I can +,-,==,* two matrices. 我正在尝试设置函数并执行一些重载操作,以便可以+,-,==,*两个矩阵。 I have encountered a problem at the first operation overload: addition. 我在第一次操作重载时遇到了一个问题:加法。

My program works until i try to add 2 matrices. 我的程序可以正常工作,直到我尝试添加2个矩阵。

Thanks for help. 感谢帮助。

include<iostream>
using namespace std;

class matrixType
{
private:
    int rows,cols;
    int** matrix;
public:

    matrixType( int r, int c)
    {
        rows=r;
        cols=c;
        matrix = new int*[rows];
        for(int i = 0; i < rows; ++i)
            matrix[i] = new int[cols];
    }

    ~matrixType()
    {
        for(int i = 0; i < rows; ++i) 
        {
            delete [] matrix[i];
        }
        delete [] matrix;
    }

    matrixType operator+( matrixType m2 )
    {
        if( rows==m2.rows && cols==m2.cols)
        {
            matrixType m3(rows, cols);
            for( int i=0; i<rows; i++)
            {
                for( int j=0; j<cols; j++)
                {
                    m3.matrix[i][j]=matrix[i][j]+m2.matrix[i][j];
                }
            }
            return m3;
        }
    }

    matrixType operator-(matrixType m2)
    {
        if( rows==m2.rows && cols==m2.cols)
        {
            matrixType m3(rows, cols);
            for( int i=0; i<rows; i++)
            {
                for( int j=0; j<cols; j++)
                {
                    m3.matrix[i][j]=matrix[i][j]-m2.matrix[i][j];
                }
            }
            return m3;
        }
    }

    friend istream& operator>> (istream& stream, matrixType m)
    {
        for ( int i=0; i<m.rows;i++)
        {
            for( int j=0; j<m.cols;j++)
            {
                cout<<"Matrix"<<"["<<i<<"]"<<"["<<j<<"]"<<"=";
                stream>>m.matrix[i][j];
                cout<<endl;
            }
        }
        return stream;
    }

    friend ostream& operator<<(ostream& out, matrixType m)
    {
        for ( int i=0; i<m.rows;i++)
        {
            for( int j=0; j<m.cols;j++)
            {
                cout<<"Matrix"<<"["<<i<<"]"<<"["<<j<<"]"<<"=";
                out<<m.matrix[i][j];
                cout<<endl;
            }
        }
        return out;
    }
};

Totally different approach as alternative - based on templates: 完全不同的替代方法-基于模板:

template <size_t Rows, size_t Columns>
class Matrix
{
    int matrix[Rows][Columns];

public:
    void operator+=(Matrix<Rows, Columns> const& other)
    {
        for(size_t i = 0; i < Rows; ++i)
        {
            for(size_t j = 0; j < Columns; ++j)
            {
                matrix[i][j] += other.matrix[i][j];
            }
        }
    }

    Matrix<Rows, Columns>
    operator+(Matrix<Rows, Columns> const& other) const
    {
        Matrix<Rows, Columns> result(*this);
        result += other;
        return result;
    }

    template<size_t C>
    Matrix<Rows, C> operator*(Matrix<Columns, C> const& other) const
    {
        // just exemplary, actual implementation missing:
        return Matrix<Rows, C>();
    }

    // rest of operators coming here
};

It might or might not fit your needs, but if it does, you get the rule of three for free. 它可能满足或可能不满足您的需求,但是如果满足,您将免费获得三个规则。 Additionally you are prevented automatically from adding or multiplying matrices of non-fitting sizes. 此外,系统会自动阻止您添加或相乘非适合大小的矩阵。

On the other hand -- well, benefits always come with some cost, too... -- you lose flexibility. 另一方面-好处总是也要付出一些代价...-您失去了灵活性。 Imagine you want to place arbitrary matrices into a vector - you'd need a base class then and would have to use (smart?) pointers, adding or multiplying arbitrary matrices requires casts, ... 想象一下,您想将任意矩阵放入向量中-您需要一个基类,然后必须使用(智能?)指针,对任意矩阵进行加或乘运算需要强制转换,...

Biggest drawback, though, is that you need to know your matrix sizes at compile time - if you don't, we are out. 但是,最大的缺点是您需要在编译时知道矩阵的大小-如果您不知道,我们就会淘汰。

By the way, adding/multiplying - in your original implementation, you do not return anything if matrix sizes do not match! 顺便说一句,加/乘-在原始实现中,如果矩阵大小不匹配,则不返回任何内容! You should return some kind of sentinel then, eg a 0x0 matrix - or possibly even better: throw some appropriate exception. 然后,您应该返回某种类型的哨兵,例如0x0矩阵-甚至可能更好:抛出一些适当的异常。

This sound like a case of rule of three violation. 这听起来像是违反三个规则的情况。

You need to implement a copy constructor: 您需要实现一个复制构造函数:

matrixType(const matrixType&)

And a copy assignment operator: 和一个副本分配运算符:

matrixType operator=(const matrixType&)

And for C++11 it might be a good idea to also implement the move constructor and move assignment operator. 对于C++11 ,最好实现move构造函数和move赋值运算符。

matrixType(matrixType&&)
matrixType& operator=(matrixType&& other)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM