Home > Software design >  Using an Array from my class in other parts of my code
Using an Array from my class in other parts of my code

Time:11-22

I declared 2 arrays in the top of my code as a class. I am trying to reference these later on in a seperate function but for some reason it isn't reading it.

Tried using Vectors and arrays, etc. looked into pointers. different headers. not sure what I'm missing.

class Cards {
  // Public Data to keep variables open thourghout the Code
  // We would use private if sensitve data was involved
 public:
  string deck[13] = {"1", "2", "3", "4",  "5", "6",
                     "7", "8", "9", "10", "J", "A"};
  string suit[4] = {"Hearts", "Spades", "Diamonds", "Clubs"};

  vector<string> cardVal = {"Ace",  "Two",   "Three", "Four", "Five",
                            "Six",  "Seven", "Eight", "Nine", "Ten",
                            "Jack", "Queen", "King"};
  vector<string> suitvec = {"Hearts", "Spades", "Diamonds", "Clubs"};
};

int DrawCard() {
  srand(time(0));
  int RandomDraw = rand() % 13;
  int RandomSuit = rand() % 4;
  int handValue = 0;

  for (int i = 0; i < 1; i  ) {
    cout << deck[RandomDraw];
    cout << suit[RandomSuit];
  }

  return handValue;
}

CodePudding user response:

Since you are creating the function drawCard outside of the class you'll need to create an object of type cards to access deck and suit.

int DrawCard() {
  srand(time(0)); 
  int RandomDraw = rand( ) % 13;
  int RandomSuit = rand() % 4;
  int handValue = 0;
  Cards c;


  for(int i = 0; i < 1; i  ) {
  cout << c.deck[RandomDraw];
  cout << c.suit[RandomSuit];

  } 

The alternative is to make those fields static.

However as pointed out in the comments drawCards should be a member function.

CodePudding user response:

As pointed out, the function DrawCard is defined outside the class. The problem arises when you want to access the class member variables directly by their identifier.

There are several solutions to this problem.

  1. Define the function as a class member function.

    class Cards {
        .
        .
    
    public:
        int DrawCard(void);
    };
    
    int Cards::DrawCard(void) {
        .
        .
    }
    
  2. Instantiate the class in the function, then call the member variables.

    class Cards {
        .
        .
        .
    };
    
    int DrawCard(void) {
        Cards cards;
        .
        .
        cards.deck.at(RandomDraw);
        cards.suit.at(RandomSuit);
    }
    

    Note: Always access the container data with the help of at function. It throws an exception when the data is requested to be accessed out-of-bounds, etc. Using the subscript operator to access them is unprotected.

However, it seems like the first method is what you wanted to get done. Also, always follow encapsulation and keep the fields private. Let only the member functions have access to them to communicate outside the class.

  •  Tags:  
  • c
  • Related