从另一个函数调用函数错误C++

Call function from another function error C++

我正在尝试让我的 player1Hand 功能与我的牌组功能一起使用,以便可以从牌组中抽取卡片并用于每个玩家功能。我不确定如何从另一个函数调用一个函数,因为它说, main.cpp:68:10: error: 'deck' was not declared in this scope

cout << deck[ z ].rank << " of " << deck[ z ].suit << endl;

完整代码:

#include <iostream>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <string>
#include <ctime> // time function for seed value
#include "Card.h"

using namespace std;



#define pause cout << endl; system("pause")

class CardClass {
public: 

  struct card

  {
    string rank;//this example uses C++ string notation
    string suit;
    int value;
  };
public:
  void deckFunction ();

private:

};

void CardClass::deckFunction () {
  srand(time(0));

  struct card deck[52];  // An array of cards named deck, size 52


  const string ranks[ ] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
    "Nine", "Ten", "Jack", "Queen", "King" };

  const string suits[ ] = { "Diamonds", "Hearts", "Spades", "Clubs" };

  int k = 0; 

  for ( int i = 0; i < 13; i++)
  {
    for ( int j = 0; j < 4; j++)
    {
      deck[ k ].rank = ranks[ i ];
      deck[ k ].suit = suits[ j ];
      k++;
    }
  }

}

void Players::player1hand () {

  CardClass deckFunc;
  deckFunc.deckFunction();
  int p1Chips = 10;
  int pot = 0;
  int player1bet = 0;
  srand(time(0));
  char ans;
  do {
    int z = rand () % 52;

    cout << deck[ z ].rank << " of " << deck[ z ].suit << endl;
    cout << "Place bet: ";
    cin >> player1bet;
    if (player1bet > 0) {
      pot = pot + player1bet;
      p1Chips = p1Chips - player1bet;
      cout << pot << endl;
      cout << p1Chips << endl;

    }
    else {
      cout << "Player 1 folds.";
      cin >> ans;
    }
    cout << "Would you like another card? " << endl;
    cin >> ans;
  } while (ans == 'y');

}



int main()
{
  Players player1;
  player1.player1hand();

  pause;

  return 0;

}

Card.h 文件(还没有真正使用过):

#include <iostream>
using namespace std;

class Players
{
public:
void player1hand ();
void player2hand ();
void player3hand ();
void player4hand ();
void player5hand ();
void player6hand ();
private:


};

我知道一些功能,class 交互现在有点草率,但我只是想让一切正常工作。所以基本上,我需要玩家 class 从牌组 class 拿一张牌,然后让他们下注,然后重复这个过程。感谢您的帮助!

你有

struct card deck[52];

这在函数 CardClass::deckFunction 中定义了 deck。这不会使 deckPlayers::player1hand 中可见。

您可以通过将 deck 作为参数传递给 player1Hand 来解决此问题。

更改 Players 的成员函数以包含一个附加参数。

class Players
{
   public:
      void player1hand (card deck[]);
      void player2hand (card deck[]);
      void player3hand (card deck[]);
      void player4hand (card deck[]);
      void player5hand (card deck[]);
      void player6hand (card deck[]);
   private:
};

然后,更新函数的实现。更新后的 Players::player1hand 看起来像:

void Players::player1hand (card deck[]) {
   // ... include the body of the function
}

你的

struct card deck[52];

仅在 void CardClass::deckFunction () 可见,而您正试图在 void Players::player1hand()

外部访问它