【问题标题】:How can I use void printMatrix( ostream& os = cout ) const?如何使用 void printMatrix(ostream& os = cout) const?
【发布时间】:2013-03-12 23:26:30
【问题描述】:

我正在学习 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”的参数 1 提供了默认参数 [-fpermissive] 在 Matrix.cpp:8:0 包含的文件中: Matrix.h:25:10:错误:在'void Matrix::printMatrix(std::ostream&) const' [-fpermissive] 中的先前规范之后

【问题讨论】:

  • 错误是什么?
  • 您有#include &lt;iostream&gt; 指令吗?您是否将名称从 std 命名空间导入到全局命名空间中?最简单的方法是使用using namespace std,但这是不好的编程习惯。尝试使用完全限定名称:std::coutstd::ostream 而不仅仅是 coutostream
  • 我已经包含了 ,并且我在代码中包含了 using namespace std

标签: c++


【解决方案1】:

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

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


    ...
}

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

【讨论】:

  • @FazakasIstvan:很高兴它有帮助:)
【解决方案2】:

该函数有一个输出流作为参数,并且默认有标准输出 (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);

【讨论】:

  • 不,它不需要它。这就是os = cout 所做的;如果没有提供输出流,它会提供一个默认值。
  • @ValekHalfHeart 我猜这是对消失的评论的回复?
  • 没有。这是对您答案第一行的回复。
  • @ValekHalfHeart 你是对的。我试图在代码示例中说明用法,但开头的句子令人困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
相关资源
最近更新 更多