簡體   English   中英

如何在 C++ 中調用析構函數

[英]How to call a destructor in C++

我試圖在這里找到答案,但我沒有找到任何工作。 我這里有一個二十一點游戲。 我的下一步是開始在游戲中添加資金余額並下注,但在此之前,我正在研究我的“再玩”選項。 就目前而言,當玩家再次玩時,他們的手牌與上一輪相同。 我相信我需要調用析構函數來刪除當前的手牌和套牌,然后重新開始。 不幸的是,我無法弄清楚如何清除手並從新的甲板開始。 我試圖在名為 play 的函數中調用這個析構函數。 在這里,如果玩家說他們想再玩一次,我會刪除手牌和套牌,然后在主界面中重建它們。 但是我已經嘗試過“deck.Deck::~Deck()”和“deck.~Deck()”,但都沒有奏效。 我會上傳我所有的代碼。 如果有人有任何想法,請幫助我。 我知道析構函數應該在它超出范圍時由編譯器調用,但是如何在游戲仍在運行且主要仍在運行時從新的手牌和套牌開始? 感謝您的幫助。

這是我的頭文件:

//blackjack.h A class to represent a deck of cards
#include <iostream>
#include <string>


class Card { 
  friend class Deck;
  private:
    int card_index; //card number 0 to 51
    Card(int index) { card_index = index; } //made this private so user can't say card at index 100..can use it because of friend class
  public:
    Card() { card_index = 52; }
    char suit() const;
    char value() const;
    std::string str() const;
    int getValue(std::string c);
};

class Deck {
  private:
    Card cards[52];
    int pos;
  public:
    Deck();
    ~Deck();
    Card deal() { return cards[pos++]; };
    void shuffle();
    int size() const { return 52 - pos; };
};

class Hand {
  friend class Deck;
  friend class Card;
  private:
    int handSize;
    int ctotal;
    Card myCards[52];

  public:   
    Hand() { handSize = 1; };
    ~Hand();
    Hand(int n) { handSize = n; };
    void dealFrom(Deck& d);
    void reveal();   
    int total();
    void hit(Deck& d);
};

std::ostream& operator<< (std::ostream& out, const Card& c);

這是我的實現文件:

//blackjack.cpp - Implementations of the Deck and Card classes
#include "blackjack.h"
#include <cstdlib>



char Card::suit() const {
  static char suits[] = { 'H', 'S', 'D', 'C' };
  //return card_index < 52 ? suits[card_index % 4] : 'X';
  return suits[card_index % 4];
}

char Card::value() const {
  static char values[] = 
    { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };
    //return card_index < 52 ? values[card_index / 4] : 'X';
    return values[card_index / 4];
}

std::string Card::str() const {
  std::string s;
  s += value();
  s += suit();
  return s;
}

Deck::Deck() {
  for (int i = 0; i < 52; i ++) {
    cards[i] = Card(i);
  }
  pos = 0;
}

void Deck::shuffle() {
  for (int i = 0; i < 52; i++) {
    int j = rand() % 52;
    Card tmp = cards[i];
    cards[i] = cards[j];
    cards[j] = tmp;
  }
  pos = 0;
}

std::ostream& operator<< (std::ostream& out, const Card& c) {
  out << c.str();
  return out;
}

int Card::getValue(std::string c) {
  char v = c[0];
  int val = v - '0';
  if (val > 9) {
    switch(v){
      case 'T':
      case 'J':
      case 'Q':
      case 'K':
        val = 10;
        break;
      case 'A':
         val = 11;
    }
  }
  return val;

}
void Hand::dealFrom(Deck& d) {
  for(int i = 0; i < handSize; i++)
      myCards[i] = d.deal();
}

void Hand::reveal(){ 
  for (int i = 0; i < handSize; i++) 
    std::cout << myCards[i] << " " << std::endl;
}

void Hand::hit(Deck& d) {
  int index = handSize;
  handSize++;
  myCards[index] = d.deal();

}

int Hand::total() {

  ctotal = 0; //reset card total

  for (int i = 0; i < handSize; i ++) {
    ctotal += myCards[i].getValue(myCards[i].str());
  }

  for (int i = 0; i < handSize; i ++) { //make ace 1 if over 21
    if ( (myCards[i].getValue(myCards[i].str()) == 11) && ctotal > 21 )
      ctotal = ctotal - 10;
  }

  return ctotal;

}

這是我的主要程序:

#include "blackjack.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void play(bool& quitGame, bool& quit, Deck& deck, Hand& d,Hand & p) { //function to play again?
  char ans;
  cout << "\nPlay Again? y or n" << endl;
  cin >> ans;
  if (ans == 'y' || ans == 'Y') {
    quitGame = false;
    quit = false;
    deck.Deck::~Deck(); //trying to delete the deck and hand objects before next game
    d.Hand::~Hand();
    p.Hand::~Hand();
    //deck.~Deck();
    //d.~Hand();
    //p.~Hand();

  } else if (ans == 'n' || ans == 'N')
    quitGame = true;
  else {
    cout << "Incorrect response." << endl;
    play(quitGame, quit, deck, d, p);
  }

}

void reveal(Hand& d, Hand& p) { //function to reveal the hand
  cout << "Your hand is: " << endl;
      p.reveal();
      cout << "Your total is: " << endl;
      cout << p.total() << endl;
      cout << endl;
      cout << "Dealer's hand is: " << endl;
      d.reveal();
      cout << "Dealer's total is: " << endl;
      cout << d.total() << endl;
}
void autoComplete(Hand& d, Hand& p, bool& quit, bool& quitGame, Deck& deck) { //function to check for blackjack and over 21
  if (p.total() == 21 && d.total() == 21) {
    cout << "You and dealer both hit blackjack. You tied." << endl;
    quit = true;
    play(quitGame, quit, deck, d, p);
  } else if(p.total() == 21) {
    cout << "Congratulations, you hit blackjack. You win!" << endl;
    quit = true;
    play(quitGame, quit, deck, d, p);
  } else if(d.total() == 21) {
    cout << "Sorry. Dealer hit blackjack. You lose." << endl;
    quit = true;
    play(quitGame, quit, deck, d, p);    
  } else if (p.total() > 21 && d.total() > 21) {
    cout << "You and dealer both passed 21. Game is a tie." << endl;
    quit = true;
    play(quitGame, quit, deck, d, p);
  } else if (p.total() > 21 && d.total() < 21) {
    cout << "You passed 21. You lose.";
    quit = true;
    play(quitGame, quit, deck, d, p);
  } else if (d.total() > 21 && p.total() < 21) {
    cout << "Dealer passed 21. You win.";
    quit = true;
    play(quitGame, quit, deck, d, p);
  }
}

int main() {
  srand(time(0));

  char response; // variable to hit or stand
  bool quit = false; //variable to end the current round
  bool quitGame = false; //variable to play game again

  while (quitGame == false) { //while the player wants to continue playing

    Deck deck; //create deck
    Hand p(2); //player's hand
    Hand d(2); //dealer's hand
    deck.shuffle(); //shuffle deck
    p.dealFrom(deck); //deal from deck
    d.dealFrom(deck);

    while (quit == false) { //while the round isn't over
      reveal(d, p); //reveal the cards
      autoComplete(d, p, quit, quitGame, deck); //check for blackjack and over 21


      if(p.total() < 21 && quit == false) { //if games not over and player is under 21
        cout << "Press 'h' to hit or 's' to stand." << endl;
        cin >> response; 
      }

      if (response == 'h') {
        cout << " " << endl;
        p.hit(deck);
        if (d.total() < 17) //if the dealer hasn't hit 17, dealer hits deck
          d.hit(deck);
      }
      if (response == 's') {
        cout << " " << endl;
        while (d.total() < 17){ //if the dealer hasn't hit 17, keep hitting deck
          d.hit(deck);
        }
        if (d.total() < 21 && p.total() < 21) {
          if (d.total() > p.total() && quit == false) { //if dealers total is higher than players total
            reveal(d, p);
            cout << "\nDealer wins!" << endl;
            quit = true;
            play(quitGame, quit, deck, d, p);
          } else if (p.total() > d.total() && quit == false) { //if players total is higher than dealers total
            reveal(d, p);
            cout << "\nYou win!" << endl;
            quit = true;
            play(quitGame, quit, deck, d, p);
          } else if (p.total() == d.total() && quit == false) { //if dealers total equals players total
            reveal(d, p);
            cout << "\nYou tied." << endl;
            quit = true;
            play(quitGame, quit, deck, d, p);
          }
        }
      } 
    }
  }    

  return 0;

}

語法:

Class obj;
obj.~Class();

將調用該對象的析構函數。 但是,你應該這樣做。 舉個例子:

#include <cstdio>

class Foo {
public:
    Foo() {}
    ~Foo() {
        printf("Destroya\n");
        if (foo_m) delete foo_m;
    }
private:
    int* foo_m = new int(42);
};

int main() {
    Foo foo;
    foo.~Foo();
}

代碼鏈接

從輸出中可以看出,析構函數被調用了兩次。 第一次當我們手動“銷毀”一個對象時,當它真正離開堆棧時又一次。

幾乎從不手動調用析構函數。 該對象不會消失,您只會破壞其狀態並獲得未定義的行為。 您真正想要的可能是像clear()reset()函數之類的東西來重新初始化狀態。 或者按照評論中的建議,您可以將分配一個默認對象移動到您已經存在的對象中以重置狀態,而無需編寫額外的功能。

析構函數通常不是您手動調用的。 對於堆棧上的內存,當對象超出范圍時會自動調用析構函數。 對於堆上的內存,當您使用delete時會調用析構函數。 在這種情況下,您實際上並不想刪除手,而只是想重置它。 deck = Deck()將“重置”它並為您提供默認構造的 Deck 對象。

我如何[做]在游戲仍在進行中並且主要仍在運行時從新的手牌和套牌開始

從根本上說,您只需要在一個地方調用play :在main的內循環之外(“當回合未結束時”)。 除了所有重復的代碼之外,您的問題是當玩家想再次玩游戲時,您將quitquitGame都設置為false ,這樣內循環就永遠不會終止並且您的牌組永遠不會被重新洗牌。

其他問題,留給讀者作為練習:可以在給response賦值之前閱讀它。 你的shuffle程序不是很好,因為很多牌都不會被移動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM