使用运算符重载添加矩阵

时间:2017-11-03 17:07:23

标签: c++ operator-overloading

我做了一个使用运算符重载的矩阵加法程序。我已经完成了程序,但它没有为矩阵B输入。请查看程序并提供帮助。在这里,矩阵输入主要用两个不同的对象,然后我使用运算符重载'+'' +添加2个对象成员,10个用于显示'<<<<"&#运算符过载。

    #include<iostream>
    using namespace std;
    int s;
    class matrix
    {
    public:
        int **m1,**m;
        friend matrix operator +(matrix &t,matrix &t1);
        friend ostream& operator << (ostream &out,matrix &t);
    };
    matrix operator +(matrix &t,matrix &t1)
    {
        for(int x=0;x<s;x++)
        {
            for(int y=0;y<s;y++)
            {
                t.m1[x][y]+=t1.m1[x][y];
            }
        }
    }
    ostream& operator << (ostream &out,matrix &t2)
    {
        for(int p=0;p<s;p++)
        {
            for(int q=0;q<s;q++)
            {
                out<<t2.m[p][q]<<"  ";
            }        
           out<<endl;
        }
    }
    int main()
    {
        cout<<"Enter the size of matrices(SQUARE MAT ONLY):: ";
        cin>>s;
        matrix t,t1,t2;
        for(int i=0;i<s;i++)
        {
            for(int j=0;j<s;j++)
            {
                cout<<"Enter value ("<<i+1<<","<<j+1<<") for matrix A::";
                cin>>t.m1[i][j];
            }
        }
        for(int i=0;i<s;i++)
        {
            for(int j=0;j<s;j++)
            {
                cout<<"Enter value ("<<i+1<<","<<j+1<<") for matrix B::";
                cin>>t1.m1[i][j];
            }
        }
        t2=t+t1;
        cout<<t2;
    }

2 个答案:

答案 0 :(得分:2)

您实施的内容更像+=运算符。它会就地修改t,并且甚至不返回任何内容,尽管它有签名(转向并注意编译器警告!)。所以这是未定义的行为。

简而言之,+运算符应该创建并返回一个新的矩阵对象。

答案 1 :(得分:0)

我假设您正在为方形矩阵创建一个类,并希望添加两个方形矩阵。我修改了您的类表示和一些代码,并提出了以下可能的解决方案。

 #include<iostream>
 using namespace std;
 #define s 3 //this is just an example value of s. This should generally be a defined as all caps. Eg: #define MATRIX_SIZE 3
 class matrix
 {
        public:
        int  **m;
        matrix()
        {
            m = new int*[s];
            for(int i = 0 ; i < s ; i++)
            {
                m[i] = new int[s];
            }
        }
        friend matrix operator +(matrix &m1, matrix &m2);
        friend ostream& operator << (ostream &os, matrix &m1);

};

matrix operator +(matrix &m1, matrix &m2)
{
    matrix m3 = matrix();


    for(int i = 0 ;i < s ; i++)
    {
        for(int j = 0 ; j < s ; j++)
        m3.m[i][j] = m1.m[i][j] + m2.m[i][j];


    }
    return m3;
}

ostream& operator <<(ostream &os, matrix& m)

{
    for(int i = 0 ; i< s ; i++)
    {
        for(int j = 0 ; j < s ; j++)
        os << m.m[i][j] <<" ";
        os << "\n";
    }
    return os;
}

int main()
{
    matrix m1 = matrix();
    matrix m2 = matrix ();
    for(int i = 0 ; i < s ; i++)
    {
    for(int j = 0 ;j < s ; j++)
    {
         m1.m[i][j] = i+j;
      m2.m[i][j] = i+j;
    }

    }
    matrix m3 = m1 + m2;
    cout << m3;
    return 0;
}