【问题标题】:C++ stream insertion operator returns bit instead of stringC ++流插入运算符返回位而不是字符串
【发布时间】:2021-04-08 04:45:28
【问题描述】:

我的问题是,当我尝试通过 cout 使用它而不是来自输出

template <class V>
//friend ostream& operator<<(ostream&, const Report<V>&);
//CORRECTED VERSION:
friend ostream& operator<<(ostream&, const Report<V>*);
...
template <class V>
ostream& operator<<(ostream& output, const Report<V>& b)
{
  for(int i = 0;i<b.rows.size();i++){
    output << b.rows[i].row <<endl;// b.rows[i].row is a 1 line string
  }
  return output;
}
...
//how I am using the stream insertion operator in a seperate function:

void Main::print(Report<int> *r) {
    cout << r <<endl;//I have tried changing to &r, *r but no luck
}

【问题讨论】:

  • 相关代码不足。您也可以尝试将您的endl 更改为'\n'。您很少需要手动刷新,并且在尝试插入流时不断刷新似乎不太理想。但是,最大的问题是您为Report&lt;V&gt; 重载了operator&lt;&lt;(),但通过了Report&lt;V&gt;*。你只是在打印一个地址。
  • @sweenish 你认为我可以用 && 取消引用指针吗?那行得通吗

标签: c++ io


【解决方案1】:

我的问题是尝试使用带有地址的流插入的指针对象,在将流插入运算符更改为采用指针后一切正常。

【讨论】:

    猜你喜欢
    • 2012-02-06
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2011-11-15
    • 1970-01-01
    • 2020-10-15
    • 2019-09-15
    相关资源
    最近更新 更多