如何使用void printMatrix( ostream& os = cout ) const?

How can I use void printMatrix( ostream& os = cout ) const?

本文关键字:cout const os void 何使用 printMatrix ostream      更新时间:2023-10-16

我正在学习c++,我有一个任务,用这个函数做一些打印,我不明白如何使用ostream。有人能帮帮我吗?

    void Matrix::printMatrix( ostream& os = cout ) const{
    for(int i=0; i<n; i++)
      for(int j=0; i<m; j++)
        os<<elements[i][j]<<"n";
    }

我试过这样做,但它抛出了一些错误,我不知道如何处理这个。错误:

Matrix.cpp:47:48:错误:' void Matrix::printMatrix(std::ostream&) const ' [-fpermissive]的参数1的默认参数包含在Matrix.cpp:8:0的文件中:Matrix.h:25:10: error: after previous specification in ' void Matrix::printMatrix(std::ostream&) const ' [-fpermissive]

你应该指定函数的默认实参在声明和定义中:

class Matrix
{
    // ...
    // Default argument specified in the declaration...
    void printMatrix( ostream& os = cout ) const;
    // ...
};
// ...so you shouldn't (cannot) specify it also in the definition,
// even though you specify the exact same value.
void Matrix::printMatrix( ostream& os /* = cout */ ) const{
//                                    ^^^^^^^^^^^^
//                                    Remove this

    ...
}

或者,您可以在定义中保留默认实参规范,并在声明中省略它。重要的是你不能两者都有。

该函数有一个输出流作为参数,并将标准输出(std::cout)作为默认值(尽管在函数定义中错误地指定,而不是在声明中)。你可以这样做:

// use default parameter std::cout
Matrix m + ...;
m.printMatrix();
// explicitly use std::cout
m.printMatrix(std::cout);
// write to a file
std::ofstream outfile("matrix.txt");
m.printMatrix(outfile);