C ++使用运算符重载

时间:2018-11-09 13:12:56

标签: c++ operator-overloading

#include <iostream>


using namespace std;


class   matrix   

{

private:

    int row;

    int col;

    int **data;

public:

    matrix(int r=0,int c=0)

    {
        row=r;
        col=c;
        data=new int*[row];
        for(int i=0; i<row; i++)
        {
            data[i]=new int [col];
        }
    }

    friend void createMatrix (int row, int col, int num[], matrix& mat);

    friend istream &operator>>(istream&in,matrix &mat);

    friend ostream &operator<<(ostream&out,matrix &mat);

    matrix operator+ (matrix mat)
    {
        matrix z(row,col);
        if((row==mat.row)&&(col==mat.col))
        {
            for(int i=0 ; i<row ; i++)
            {
                for(int j=0 ; j<col; j++)
                {
                    z.data[i][j]=data[i][j]+mat.data[i][j];
                }
            }
        }
        else
        {
            cout<<"Matrix that aren't the same size can't be added"<<endl;
        }
        return z;
    }        

};                   

 ostream &operator<<(ostream&out,matrix &mat)        

{

    for(int i=0; i<mat.row; i++)
    {
        for(int j=0; j<mat.col; j++)
        {
            out<<mat.data[i][j]<<" ";
        }
        out<<endl;
    }
    return out;
}

istream &operator >>(istream &in,matrix& mat)

{

    cout<<"Enter the size of your matrix"<<endl;
    in>>mat.row;
    in>>mat.col;
    mat.data=new int*[mat.row];
    cout<<"Enter the elements of your matrix"<<endl;
    for(int x=0; x<mat.row; x++)
    {
        mat.data[x]=new int[mat.col];
    }
    for(int i=0; i<mat.row; i++)
    {
        for(int j=0 ; j<mat.col; j++)
        {
            in>>mat.data[i][j];
        }
    }
    return in;
}

int main()

{

    matrix x,y;

    cin>>x>>y;
    cout<<x+y<<endl;
    return 0;
}

void createMatrix (int row, int col, int num[], matrix& mat)

{

    mat.row = row;
    mat.col = col;
    mat.data = new int* [row];

    for (int i = 0; i < row; i++)
        mat.data[i] = new int [col];

    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            mat.data[i][j] = num[i * col + j];
}

当我尝试运行时,出现错误:

|83|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'matrix')|

但是当我将主要更改为:

matrix x,y,z;
cin>>x>>y;
z=x+y;
cout<<z<<endl;
return 0;

我没有问题,尽管我不能使用它,因为我必须做大约14种不同的运算符重载,我不确定是代码错误还是编译器错误。知道我该怎么解决吗?

2 个答案:

答案 0 :(得分:2)

您已将operator<<定义为采用矩阵引用

ostream &operator<<(ostream&out,matrix &mat)

表达式的输出

x+y

是一个临时对象,不能作为参考传递。您必须将其作为const引用const matrix& mat或按值matrix mat传递。在这种情况下,您应该使用const引用,以避免复制整个矩阵。

答案 1 :(得分:1)

使用常量矩阵:

ostream &operator<<(ostream&out,const matrix &mat)

这将创建一个临时矩阵

cout<<x+y<<endl;

它不能仅由ref传递。就其输出而言,它还是应该为const ref。

相关问题