enum declaration

Hi guys
I am new to c++. I've problem using enum type. I actually dont understand how i can declare it in header and how to use it in source file. This is what i think must work but it didnt.
1
2
3
4
5
6
7
8
9
10
11
12
13
Header:

#ifndef CARD_H_
#define CARD_H_

class Card {
public:
	Card();
	virtual ~Card();
	enum suits;
	enum ranks;
	void print(void);
};


Source file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include "Card.h"

using namespace std;
Card::Card() {
	enum suits = {Clubs, Diamonds, Hearts, Spades};
	enum ranks = {ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king};
}

Card::~Card() {
	// TODO Auto-generated destructor stub
}


void Card::print(){
	cout << three;
}

#endif /* CARD_H_ */

To test it:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "Card.h"

using namespace std;


int main()
{
	Card a;
	a.print();


}
First, don't use the =. An enum is not an array so the equal sign is not used.

Also, I've never seen enum used that way I'm not sure if it would work. In terms of useage, I ussually see enum declared globaly and limited with a namespace.

I would do the following in the header:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Header:

#ifndef CARD_H_
#define CARD_H_

namespace suits
{
	enum s {Clubs, Diamonds, Hearts, Spades};
}
namespace ranks
{
	enum r {ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king};
}

class Card {
public:
	Card();
	virtual ~Card();
	void print(void);
};


In the worst (or maybe best?) case, you can declare the enum as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
Header:

#ifndef CARD_H_
#define CARD_H_

class Card {
public:
	Card();
	virtual ~Card();
	enum suits {Clubs, Diamonds, Hearts, Spades};
	enum ranks {ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king};
	void print(void);
};

Either way, take it out of the cpp file.
Last edited on
i m not allowed to use namespace
thx anyway
You don't NEED the namespace, that was just to help limit the scope of a global declaration. You can remove that part. Or try the second suggestion for a minimal change on your code (no equal sign).
Topic archived. No new replies allowed.