0

我很难弄清楚如何为嵌套枚举类型的类 Card 重载后缀增量运算符。此外,我也很难获得为这门课工作的副本作业。我收到以下错误“运算符 ++ 必须采用一个或零个参数。” 然后,当我尝试提供作业时,我得到

no match for operator= in ((deck*)->this)->Deck::deckArr = operator new 

class Card {
  public:
    enum Suit {
      SPADES,
      HEARTS,
      CLUBS,
      DIAMONDS
    };

    enum Spot {
      DEUCE,
      THREE,
      FOUR,
      FIVE,
      SIX,
      SEVEN,
      EIGHT,
      NINE,
      TEN,
      JACK,
      QUEEN,
      KING,
      ACE
   };

   Card();
   Card(Card&);
   Card(Suit&, Spot&);
   ~Card();

   Suit& operator++(Suit&,int);
   Spot& operator++(Spot&,int);
   Card& operator=(const Card&);

 private:
   Spot _spot;
   Suit _suit;
};

Card::Suit& Card::operator++(Card::Suit &s, int) {Card::Suit oldsuit = s;
                                            s = (Card::Suit)(s+1);
                                            return oldsuit;}
Card::Spot& Card::operator++(Card::Spot &sp, int){Card::Spot oldspot = sp;
                                            sp = (Card::Spot)(sp+1);
                                            return oldspot;}
Card& Card::operator=(const Card &c){_spot = c._spot; _suit = c._suit; return *this;}


#include "card.h"

class Deck {
 public:
    Deck();
    Deck(Deck&);
    ~Deck();

    void createDeck();
    void shuffleDeck(int);
 private:
    static const int DECK_SIZE = 52;
    Card deckArr[DECK_SIZE];
};

void Deck::createDeck(){
    int x = 0;
    for(Card::Suit s = Card::SPADES; s <= Card::HEARTS; s++){
        for(Card::Spot n = Card::DEUCE; n <= Card::ACE; n++, x++){
             deckArr[x] = new Card(s, n);
        }
    }
}
4

2 回答 2

4

问题是您无法在此处使用成员运算符。成员运算符始终对它所属的类进行操作,并且由于您希望它对枚举而不是类进行操作,因此它不能成为成员。

如果你想让 ADL 找到它,你必须让它成为朋友,以便在类中声明(并可能定义它):

friend Suit& operator++( Suit& s )
{
    s = static_cast<Suit>( s + 1 );
    return s;
}
friend Suit operator++( Suit& s, int )
{
    Suit result( s );
    s ++;
    return result;
}

Spot 也是如此。

您还必须决定在迭代结束时要做什么。转换s + 1回枚举类型是未定义的行为,至少在Suit. 一个常见的约定是在末尾添加一个额外的值;例如END_SuitEND_Spot。这允许简单和安全的迭代:

for ( Suit s = SPADES; s != END_Suit; ++ s ) // ...

否则,它会变得棘手。

于 2013-08-13T14:20:28.050 回答
1

超载有两种方式operator++

Card::Suit operator++(int){ } //would be suit++

Card::Suit& operator++() { } //would be ++suit

operator++除了虚拟参数(通常)之外,您不得将任何内容传递给,int并且通常您不会reference在后缀中传回 a 。

有关一些信息,请参见此处

于 2013-08-13T14:09:21.837 回答