C++ Deck成員函數(shù)

2023-03-20 16:24 更新

有了Deck對象之后,把所有從屬于Deck的函數(shù)放入其結(jié)構(gòu)定義中也是情理之中的事了??匆幌碌侥壳盀橹刮覀兌x的函數(shù),很明顯12.7節(jié)的printDeck函數(shù)可以作為候選加進來。下面將printDeck重寫為成員函數(shù):

void Deck::print () const {
  for (int i = 0; i < cards.length(); i++) {
    cards[i].print ();
  }
}

通常,引用當(dāng)前對象不需要使用點記號。

其他幾個函數(shù),至于是否應(yīng)將它們變?yōu)镃ard或Deck的成員函數(shù),還是作為以Card或Deck變量為參數(shù)的非成員函數(shù),并非顯而易見的。比如上一章以一個Card變量和一個Deck變量為參數(shù)的find函數(shù),將它變?yōu)镃ard或Deck類型的成員函數(shù)都是合理的。作為練習(xí),請重寫find函數(shù),其參數(shù)為Card類型,使之成為Deck的成員函數(shù)。

將find改寫為Card的成員函數(shù)需要一些小技巧,這是我寫的版本:

int Card::find (const Deck& deck) const {
  for (int i = 0; i < deck.cards.length(); i++) {
    if (equals (deck.cards[i], *this)) return i;
  }
  return -1;
}

一個技巧是,必須使用this關(guān)鍵字來引用調(diào)用find函數(shù)的對象;再就是在C++中定義相互引用的結(jié)構(gòu)也需要一點技巧,因為編譯器正在讀取第一個結(jié)構(gòu)定義時還不知道第二個結(jié)構(gòu)的定義。

一種解決方案是,在Card定義之前先聲明Deck,以后再給出Deck的定義。

// 聲明Deck結(jié)構(gòu),這里不定義declare that Deck is a structure, without defining it
struct Deck;

// 這樣我們就可以在Card的定義中引用Deck
struct Card
{
  int suit, rank;
  Card ();
  Card (int s, int r);
  void print () const;
  bool isGreater (const Card& c2) const;
  int find (const Deck& deck) const;
};

// 后面給出Deck的定義
struct Deck {
  apvector<Card> cards;

  Deck ();
  Deck (int n);
  void print () const;
  int find (const Card& card) const;
}; 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號