1

我在我的代码中编写了两个覆盖运算符(<< 代表西装,<< 代表卡片),它有时似乎不起作用。我试图在覆盖运算符 << for 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;
}
4

1 回答 1

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 并输出数字。

于 2013-10-31T04:18:29.757 回答