使用枚举变量作为类数据成员会产生错误

abc*_*cde 1 c++

版本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);
}
Run Code Online (Sandbox Code Playgroud)

版本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);
}
Run Code Online (Sandbox Code Playgroud)

错误:

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)
Run Code Online (Sandbox Code Playgroud)

请告诉我两个实例中的更正,以便我能一劳永逸地理解这个概念.真的很感激.

πάν*_*ῥεῖ 6

对于你的第一种情况,代码编译就好了(在修复main()返回类型之后).我不知道你在困扰哪些错误.


对于第二种情况,枚举在类的范围内声明

class Batsman {
public:     
    enum Hand {RIGHT,LEFT};
    // ...
};
Run Code Online (Sandbox Code Playgroud)

所以你必须提供范围限定符main():

int main() {
    Batsman B1("Ryder",Batsman::LEFT);
                    // ^^^^^^^^^
    Batsman B2("McCullum",Batsman::RIGHT);
                       // ^^^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您应始终将其int作为返回类型main().