I am a C++ programmer and I rarely have to deal with GCC "C". I am currently converting some code from C++ to C for use with the GCC compiler.
我是一个c++程序员,我很少需要和GCC“C”打交道。我目前正在将一些代码从c++转换为C,以便与GCC编译器一起使用。
In C++ I would use the following source code. Note that I would use a class for scope.
在c++中,我将使用以下源代码。注意,我将使用一个类作为范围。
C++ Source
c++源
class Card {
public:
enum Suit {
Diamonds, Hearts, Clubs, Spades
};
};
class Weapon {
public:
enum WeaponType {
Rocks, Clubs, Guns
};
};
int main () {
Suit a = Card::Clubs;
WeaponType b = Weapon::Clubs
}
In "C" with no classes and no way of differentiation between the two different "clubs" keywords. I get the following error message when trying to compile this
在“C”中没有类,也没有区分两个不同的“俱乐部”关键词。在尝试编译时,我得到了以下错误消息。
error C2365: 'Clubs' : redefinition; previous definition was 'enumerator'
错误C2365:“俱乐部”:重新定义;先前定义的枚举器
C Source
C源
enum Suit {
Diamonds, Hearts, Clubs, Spades
};
enum WeaponType {
Rocks, Clubs, Guns
};
int main () {
Suit a = Clubs;
WeaponType b = Clubs
}
So my questions are
所以我的问题是
- How do I declare two different enum in the same file with the same keyword?
- 如何使用相同的关键字在同一个文件中声明两个不同的enum ?
- How do I add scope to the enum so I can assign different variables different enum with the same enum name?
- 如何向enum添加范围,以便使用相同的enum名称分配不同的enum变量?
3 个解决方案
#1
10
Do it just like the old days:
就像过去一样:
enum Suit {
ST_Diamonds, ST_Hearts, ST_Clubs, ST_Spades
};
enum WeaponType {
WT_Rocks, WT_Clubs, WT_Guns
};
int main () {
Suit a = ST_Clubs;
WeaponType b = WT_Clubs;
return 0;
}
#2
3
This cannot be done in standard C. From C A Reference Manual: "Identifiers declared as enumeration constants are in the same overloading class as variables functions and typedef names", so enumeration constants must be unique in a given scope.
这在标准C中是做不到的。参考手册C中说:“声明为枚举常量的标识符与变量函数和类型定义名称属于相同的重载类”,所以在给定的范围内,枚举常量必须是唯一的。
#3
2
Due to the lack of namespaces in C your only option is prefixing:
由于C中缺少名称空间,所以您唯一的选择是前缀:
enum Weapon {
WeaponRocks,
WeaponSocks,
...
};
#1
10
Do it just like the old days:
就像过去一样:
enum Suit {
ST_Diamonds, ST_Hearts, ST_Clubs, ST_Spades
};
enum WeaponType {
WT_Rocks, WT_Clubs, WT_Guns
};
int main () {
Suit a = ST_Clubs;
WeaponType b = WT_Clubs;
return 0;
}
#2
3
This cannot be done in standard C. From C A Reference Manual: "Identifiers declared as enumeration constants are in the same overloading class as variables functions and typedef names", so enumeration constants must be unique in a given scope.
这在标准C中是做不到的。参考手册C中说:“声明为枚举常量的标识符与变量函数和类型定义名称属于相同的重载类”,所以在给定的范围内,枚举常量必须是唯一的。
#3
2
Due to the lack of namespaces in C your only option is prefixing:
由于C中缺少名称空间,所以您唯一的选择是前缀:
enum Weapon {
WeaponRocks,
WeaponSocks,
...
};