14

If I have a simple class like this one for a card:

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

and I then want to create an instance of a card in another file how do I pass the enum?

#include "Card.h"
using namespace std;
int main () {
    Suit suit = Card.CLUBS;
    Card card(suit);
    return 0;
}

error: 'Suit' was not declared in this scope

I know this works:

#include "Card.h"
using namespace std;
int main () {
    Card card(Card.CLUBS);
    return 0;
}

but how do I create a variable of type Suit in another file?

Adam Stelmaszczyk
  • 19,333
  • 4
  • 67
  • 107
Spencer
  • 3,678
  • 9
  • 31
  • 43

2 Answers2

14

Use Card::Suit to reference the type when not inside of Card's scope. ...actually, you should be referencing the suits like that too; I'm a bit surprised that Card.CLUBS compiles and I always thought you had to do Card::CLUBS.

Andrew B
  • 526
  • 1
  • 6
  • 20
dash-tom-bang
  • 16,845
  • 5
  • 44
  • 59
7

Suit is part of the class Card's namespace, so try:

Card::Suit suit = Card::CLUBS;
beeduul
  • 71
  • 2
  • OMG that is just not worth the effort. I am going to use an int and put a comment in the code. Can anybody think of a card game where Clubs change, yet a full reference for the enum is needed each time? – Paul McCarthy Apr 14 '21 at 22:02