abcde
abcde

Reputation: 535

Using an enum variable as a class data member gives an error

VERSION-1:

// In this, the enum is declared globally

#include <iostream>
#include <string>

using namespace std;

enum Hand {RIGHT,LEFT};

class Batsman {
    public:
        Batsman(string s, Hand h) {
            name = s;
            hand = h; 
        }
        void setName(string s) {
            name = s;
        }
        void setHand(Hand h) {
            hand = h;
        }
        string getName() {
            return name;
        }
        Hand getHand() {
            return hand;
        }           
    private:
        string name;
        Hand hand;  
};

void main() {
    Batsman B1("Ryder",LEFT);
    Batsman B2("McCullum",RIGHT);
}

VERSION-2:

// In this, the enum is declared inside the class

#include <iostream>
#include <string>

using namespace std;

class Batsman {
    public:     
        enum Hand {RIGHT,LEFT};
        Batsman(string s, Hand h) {
            name = s;
            hand = h; 
        }
        void setName(string s) {
            name = s;
        }
        void setHand(Hand h) {
            hand = h;
        }
        string getName() {
            return name;
        }
        Hand getHand() {
            return hand;
        }           
    private:
        string name;
        Hand hand;  
};

void main() {
    Batsman B1("Ryder",LEFT);
    Batsman B2("McCullum",RIGHT);
}

Errors:

D:\\Work Space\\C++\\C.cpp: In function `int main(...)':
D:\\Work Space\\C++\\C.cpp:33: `LEFT' undeclared (first use this function)
D:\\Work Space\\C++\\C.cpp:33: (Each undeclared identifier is reported only once
D:\\Work Space\\C++\\C.cpp:33: for each function it appears in.)
D:\\Work Space\\C++\\C.cpp:34: `RIGHT' undeclared (first use this function)

Please kindly tell me the corrections in both the instances so that I can understand the concept once and for all. Will be really appreciated.

Upvotes: 1

Views: 1090

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

For your 1st case, the code compiles just fine for me (after fixing main()'s return type). I don't know which errors you're bothering about.


For your 2nd case, the enum is declared in scope of the class

class Batsman {
public:     
    enum Hand {RIGHT,LEFT};
    // ...
};

so you'll have to provide the scope qualifier in main():

int main() {
    Batsman B1("Ryder",Batsman::LEFT);
                    // ^^^^^^^^^
    Batsman B2("McCullum",Batsman::RIGHT);
                       // ^^^^^^^^^
}

Also note you always should have int as return type of main().

Upvotes: 5

Related Questions