【发布时间】: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