【问题标题】:How to modify the ostream object to create ideal cout?如何修改 ostream 对象以创建理想的 cout?
【发布时间】:2018-04-10 16:36:42
【问题描述】:

我目前正在使用 c++11,我正在开发一个朋友函数来打印出某事,但在调用打印函数之前,我需要调用类内部的一个成员函数来访问和序列化这两个数据成员。我在修改 ostream 对象时遇到问题。 代码如下:

friend ostream& operator<<(ostream& os, const Card& c) {
     c.serialize(os);
     return os;}

void NumberCard:: serialize(ostream& os) const
 {
 Color c=this->getColor();
 switch(c){
  case Color::red:  os=(os<<"R"<<this->getPoint());break;
  case Color::yellow: os=(os<<"Y"<<this->getPoint());break;
  case Color::blue: os=(os<<"B"<<this->getPoint());break;
  case Color::green: os=(os<<"G"<<this->getPoint());break;   
  default:break;}}

我当前的方法不起作用,错误是:

use of deleted function 'std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator=(const std::basic_ostream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]'

如果有人能给我一些建议,将不胜感激。

【问题讨论】:

    标签: c++11 iostream cout


    【解决方案1】:

    不要使用

    os=(os<<"R"<<this->getPoint());
    

    这是一个问题,因为标准库不支持分配给 ostream 对象。

    使用

    os << "R" << this->getPoint();
    

    【讨论】:

      【解决方案2】:

      ostream&amp; os 是对ostream 的引用。就如何使用而言,对对象的 C++ 引用应该与实际对象没有区别。这意味着不能重新分配引用 - 相反,被引用的对象被分配给而不是引用变量本身。

      ostream 使用已删除的复制赋值运算符声明,因为您无法复制流(这是有道理的)。

      将这些结合在一起,您将了解 os = ... 导致调用赋值运算符,从而导致该错误。

      事实证明,没有必要重新分配给os,因为&lt;&lt; 返回的引用首先指向同一个(变异的)ostream 对象(这样做是为了&lt;&lt;调用可以被链接)。

      然后您的开关代码简化为:

      case Color::red:    os << "R" << this->getPoint(); break;
      case Color::yellow: os << "Y" << this->getPoint(); break;
      // ...
      

      【讨论】:

      • 该错误完全是由于删除了赋值运算符。在OP的使用中,与拷贝构造函数也被删除无关。
      • 您的解释对我来说很清楚,感谢您提醒我 operator
      猜你喜欢
      • 2022-09-18
      • 2011-03-20
      • 2013-01-24
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2015-09-18
      相关资源
      最近更新 更多