如何修改ostream对象来创建理想的cout?

时间:2018-04-10 16:36:43

标签: c++11 iostream cout

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

    for ($level = ob_get_level(); $level > 0; --$level) {
        if (!@ob_end_clean()) {
            ob_clean();
        }
    }

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

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;}}

如果有人能给我一些建议,我们将非常感激。

2 个答案:

答案 0 :(得分:0)

不要使用

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

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

使用

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

答案 1 :(得分:0)

Scenario: Verify View and Write Rewiev is visible Given I am on AbanteCart Home Page When I hover over the "SKIN CARE" option Then I click on the "SUN" option Then I should see the "Flash Bronzer Body Gel" When I hover over ont the Image Then I "View and Write Rewiev" option shoulde be visible 是对ostream& os的引用。对于对象的C ++引用应该与实际对象的使用方式无法区分。这意味着无法重新分配引用 - 而是将被引用的对象分配给而不是引用变量本身。

使用已删除的复制赋值运算符声明

ostream,因为您无法复制流(这很有意义)。

将这些组合在一起,您就会明白ostream导致调用赋值运算符,从而导致该错误。

事实证明,没有必要重新分配给os = ...,因为os返回的引用首先是同一个(变异的)<<对象(这是完成,以便可以链接ostream个调用。)

您的切换代码然后简化为:

<<