c++ - 为类中的动态数组重载 cout 运算符

标签 c++ class matrix dynamic-arrays

我正在尝试使运算符重载 <<对于 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;

但这根本不会打印任何东西。似乎重载函数没有获得 C 的任何值。和 R ,但我可能是错的。有人有什么想法吗?

假设在表单上打印动态矩阵

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;
}

关于c++ - 为类中的动态数组重载 cout 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15372636/

相关文章:

c++ - 沮丧 : why: ‘A’ is an inaccessible base of ‘B’ ?

swift - 以编程方式在类外更改按钮的特性

c++ - 在 OpenGL 4.0 中是否有围绕局部坐标(即从模型 View 矩阵)旋转的标准方法?

ruby - 如何在 Ruby 中向矩阵添加列和行?

c++ - 用三种颜色 A 和 B 和 C 填充网格

c++ - map 中过期的 weak_ptr 会发生什么

c++ - 对 R 值的常量引用

oop - 类对象统一输出的matlab arrayfun

ruby - 如何包含来自其他模块的 Ruby 类扩展?

c++ - 如何应用位置变换