在C ++中重写运算符无效

象牙

我在我的代码中写了两个覆盖运算符(<<表示西装,<<表示卡),有时似乎不起作用。我尝试在Card的覆盖运算符<<中两次调用Suit的运算符。第二个没用,为什么?

class Card{ 
public:
    enum Suit{CLUBS, SPADES, HEARTS, DIAMOND};
    Card(int v, Suit s): value(v), suit(s){};
    int getValue()const{return value;}
    Suit getSuit()const{return suit;}
private:
    int value;
    Suit suit;
};

ostream& operator<< (ostream& out, Card::Suit& s){
    switch (s) {
        case 0:
            out << "CLUBS";
            break;
        case 1:
            out << "SPADES";
            break;
        case 2:
            out << "HEARTS";
            break;
        default:
            out << "DIAMOND";
            break;
    }
    return out;
}

ostream& operator<< (ostream& out, Card& c){
    Card:: Suit s = c.getSuit();
    out << s << endl;  //here it output what I want: SPADES
    out << "Card with Suit " << c.getSuit() << " Value " << c.getValue() << endl;
    return out; //here the c.getSuit() output 1 instead of SPADES, why?()
}

int main(){
    Card* c = new Card(1, Card::SPADES);
    cout << *c;
    return 1;
}
查理

尝试将西装更改为枚举类-然后它将被强类型化,而不是强制转换为int。

...
enum class Suit {CLUBS,SPADES,HEARTS,DIAMONDS};
...

ostream& operator<<(ostream& os, Card::Suit& s) {
  switch (s) {
    case Card::Suit::CLUBS:
      os << "Clubs";
      break;
...

然后在您的其他代码中,cout << c.getSuit() << endl不会隐式转换为int并输出数字。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章