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

override operator invalid in c++

本文关键字:无效 C++ 运算符 重写      更新时间:2023-10-16

我在代码中编写了两个覆盖运算符(<<用于 Suit 和 <<用于 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;
}

尝试将 suit 更改为枚举类 - 然后它将被强类型化而不是转换为 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 并输出数字。