版本-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);
}
版本-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);
}
错误:
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)
请告诉我两个实例中的更正,以便我能一劳永逸地理解这个概念。真的很感激。
答案 0 :(得分:6)
对于第一种情况,代码compiles just fine for me(在修复main()
的返回类型之后)。我不知道你在困扰哪些错误。
对于你的第二种情况,枚举是在类的范围内声明的
class Batsman {
public:
enum Hand {RIGHT,LEFT};
// ...
};
因此您必须在main()
中提供范围限定符:
int main() {
Batsman B1("Ryder",Batsman::LEFT);
// ^^^^^^^^^
Batsman B2("McCullum",Batsman::RIGHT);
// ^^^^^^^^^
}
另请注意,您应始终int
作为main()
的返回类型。