C ++运算符重载>> <<()

时间:2019-12-12 19:36:23

标签: c++ matrix operator-overloading ostream istream

Matrix.h

class Matrix {
private:
    int row;    // rows
    int col;    // columns
public:
    double** matrix;    // pointer to this matrix
    int getRow();
    int getCol();
    void randValues();


    double operator()(int y, int x);
    friend std::ostream& operator<< (std::ostream& stream, Matrix& matrix);
    istream& operator>>(istream& input, Matrix &matrix){
        for(int i=0; i<row; i++){
            for(int k=0; k<col; k++){
                input>>matrix.matrix[i][k];
            }
        }
        return input;
    }
};

对于运算符>>代码:::块说:include \ Matrix.h | 50 |错误:'std :: istream&Matrix :: operator >>(std :: istream&,Matrix&)'必须正好采用一个参数| < / p>

Matrix.cpp

ostream& operator <<(ostream& stream,  Matrix& matrix){
    for (int i=0; i < matrix.getRow(); i++){
        for (int k=0; k < matrix.getCol(); k++){
            stream << matrix.matrix[i][k] << "  " ;
        }
        stream << '\n';
    }
    return stream;
}
double Matrix::operator() (int y, int x)
{
    if( y < 0 || x < 0 || y > this->row || x > this->col)
    {
        cout << "Wrong index of Matrix()";
    }
    else
    {
        return this->matrix[y][x];
    }
}

对于运算符<<代码块,请说:Matrix.cpp | 432 |运算符的多个定义<<(std :: ostream&,Matrix&)'|

对于算符(),当我在main()中使用它时,代码块说'matx'不能用作函数|

int main(){
        Matrix *matx = new Matrix(5,5);
        matx->randValues;
        cout << matx(0,0);
}

我想问一下如何彻底声明运算符重载,如何实现运算符重载,然后如何在main()中使用它。

0 个答案:

没有答案