类中动态数组的重载计数操作符

Overload cout operator for a dynamic array in a class

本文关键字:操作符 重载 动态 数组      更新时间:2023-10-16

我试图为类中的动态数组中的cout重载操作符<<。我的类和成员函数如下:

class Matrix{
private:
    int rows;
    int columns;
    double* matrix;
public:
    Matrix();
    explicit Matrix(int N);
    Matrix(int M, int N);
    void setValue(int M, int N, double value);
    double getValue(int M, int N);
    bool isValid() const;
    int getRows();
    int getColumns();
    ~Matrix();
    friend ostream& operator<<(ostream &out, const Matrix&matrix1);

};

    Matrix::Matrix(){
    matrix = NULL;
}
Matrix::Matrix(int N){
    matrix = new double[N * N];
    rows = N;
    columns = N;
    for(int i = 0; i < N; i++){
        for(int j = 0; j < N; j++){
            if(i==j)
                matrix[i * N + j] = 1;
            else
                matrix[i * N + j] = 0;
        }
    }
}
Matrix::Matrix(int M, int N){
    matrix = new double[M * N];
    rows = M;
    columns = N;
    for(int i = 0; i < M; i++){
        for(int j = 0; j < N; j++)
            matrix[i * N + j] =  0;
    }
}
Matrix::~Matrix(){
    delete [] matrix;
}
void Matrix::setValue(int M, int N, double value){
    matrix[M * columns + N] = value;
}
double Matrix::getValue(int M, int N){
    return matrix[M * columns + N];
}
bool Matrix::isValid() const{
    if(matrix==NULL)
        return false;
    else
        return true;
}
int Matrix::getRows(){
    return rows;
}
int Matrix::getColumns(){
    return columns;
}

我已经尝试实现<<操作符如下:

ostream& operator<<(ostream &out, const Matrix&matrix1){
Matrix mat1;
int C = mat1.getColumns();
int R = mat1.getRows();
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++)
        out << mat1.getValue(i,j) << "t";
    out << endl;
}
return out;

}

并从函数中调用:

void test(){
Matrix mat1(3,4);
cout << mat1 << endl;

}

,但这根本不打印任何东西。似乎过载函数没有得到CR的任何值,但我可能错了。有人有什么想法吗?

假定以

的形式打印动态矩阵
a11     a12     a13    . . .
a21     a22     a23    . . .
.        .       .     . . .
.        .       .     . . .
.        .       .     . . .

您正在打印一个空的mat1,而不是给定matrix1

ostream& operator<<(ostream &out, const Matrix& matrix1)
{
    //Matrix mat1;   // <- Comment ythis
    int C = matrix1.getColumns(); // <<- matrix1
    int R = matrix1.getRows(); // <<- matrix1
    for (int i = 0; i < R; i++)
    {
        for (int j = 0; j < C; j++)
            out << matrix1.getValue(i, j) << "t"; // <<- matrix1
        out << endl;
    }
    return out;
}

需要打印matrix1的内容。您正在创建一个本地空矩阵mat1,并打印其内容。

ostream& operator<<(ostream &out, const Matrix& matrix1) 
{
  int C = matrix1.getColumns();
  int R = matrix1.getRows();
  for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++)
        out << matrix1.getValue(i,j) << "t";
    out << endl;
  }
  return out;
}

我没看错吧,Matrix1是operator<<但是你正在创建一个新的mat1并输出它?