【问题标题】:operator << of enum type uses the overloaded operator or not?枚举类型的运算符 << 是否使用重载运算符?
【发布时间】:2017-10-25 05:00:16
【问题描述】:

我希望这次我的问题可以更好地表述和格式化。 这是我认为不应该产生两个单独输出的代码,因为我每次(我认为)都使用重载运算符

#include <iostream>
using namespace std;

enum Etat { Intact = 5 };

class Ship {

public: 
Etat etat_;  

Ship ( Etat t = Intact) : etat_(t) {}
~ Ship() {} 

ostream& description ( ) const {  return cout <<  "Etat: " << etat_ << "   ---   ";} 
//---------------------------------------ˆˆˆˆ----
};

ostream& operator<< ( ostream& s, const Etat& etat_ ) 
{
  switch  ( etat_ )
    {
      case Intact:    s << "intact";   break;
      default:        s << "unknown state";
    }
  return s;
}

ostream& operator<< ( ostream& s, Ship n )  {  return s <<  "Etat: "  <<  n.etat_ ; }

int main()
{
  Etat etat_ = Intact;   
  cout << endl << endl << "Etat: " 
       << etat_ << "       \"cout << etat_\"" << endl << endl;

  cout << Ship(etat_) 
       << "       \"cout << Ship(etat_)\"" << endl << endl;

  cout << Ship(etat_).description() 
       << "  \"cout << Ship(etat_).description()\"" << endl << endl;

  return 0;
}

这是我在终端中得到的:

Etat: intact       "cout << etat_"

Etat: intact       "cout << Ship(etat_)"

Etat: 5   ---   1  "cout << Ship(etat_).description()"

谁能给我解释一下,为什么在最后一种情况下,它不仅取了枚举属性的整数值,而且还在测试字符串“---”后面加了一个“1”???

我唯一能想到的就是因为我在description()中使用了一个非正统的return方法,即'return cout

有没有办法强制在description()中使用操作符

谢谢

【问题讨论】:

    标签: c++ enums operator-overloading


    【解决方案1】:

    在 description() 函数中,您返回对 std::cout 的引用,并在主函数的 std::cout 调用中使用它。 operator

    ostream& description(ostream& os) const {  
        return os <<  "Etat: " << etat_ << "   ---   ";
    }
    

    那里打印出的随机“1”可能是由于您的示例中的 ostream 试图打印出对自身的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多