0

我正在尝试学习 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: 错误:在 'void Matrix::printMatrix(std::ostream&) const' [-fpermissive] 中的先前规范之后

4

2 回答 2

6

您不应声明和定义中指定函数的默认参数

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


    ...
}

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

于 2013-03-12T23:31:22.497 回答
3

该函数有一个输出流作为参数,并有标准输出 ( 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);
于 2013-03-12T23:28:00.847 回答