语法从父类访问枚举
Syntax accessing Enum from parent class
我在程序中遇到错误。显然,我缺少有关语法的内容。下面的C 代码的摘要是产生错误的最小的。
#include <iostream>
using namespace std;
class Parent
{
public:
enum MyEnum {
Value1,
Value2,
Value3
};
MyEnum* set;
};
class Child: public Parent
{
public:
Child()
{
set = new MyEnum[5];
set[0]=MyEnum.Value1;//<--Something wrong here
set[1]=MyEnum.Value2;//<--Something wrong here
set[2]=MyEnum.Value3;//<--Something wrong here
set[3]=MyEnum.Value2;//<--Something wrong here
set[4]=MyEnum.Value1;//<--Something wrong here
}
void Write()
{
for(int i=0;i<5;i++)
{
cout<< "This is " << i << ": " << set[i];
}
}
};
int main() {
Child c;
c.Write();
return 0;
}
错误与指定的语法有关。
expected primary-expression before ‘.’ token
我尝试过parent.myenum.value1,parent :: myenum.value1等。似乎没有什么是正确的。我应该如何指代父类中的特定值?
枚举不需要其价值资格,这意味着您应该这样访问它们:
set[0] = Parent::Value1;
如果您想执行资格,可以使用强烈键入的枚举。看起来这样:
enum struct MyEnum {
Value1,
Value2,
Value3
};
set[0] = Parent::MyEnum::Value1;
但是,您应该使用明确的铸件打印它们,例如:
cout << static_cast<int>(set[0]) << endl;
enum
(例如class
)定义了范围。像您使用的常规枚举一样,将其枚举者名称放在其自己的范围和包含范围的范围内。由于这是范围分辨率,而不是成员访问,因此您使用::
而不是.
。因此,您可以使用Parent::Value1
,Value1
(因为public
和protected
Parent
的名称在Child
中可见)或Parent::MyEnum::Value1
或MyEnum::Value1
。
如果要禁止第一个或两个选项,则应使用enum class
而不是enum
。
相关文章:
- 如何正确实现和访问运算符的各种自定义枚举器
- 访问在 C++ 结构中声明的枚举变量
- 如何确保 Visual C++ 不允许作用域枚举访问?
- 通过包装器从 C 访问C++ API 时,如何访问枚举类型
- 从类访问枚举成员
- 如何通过索引访问枚举类
- 在类访问混淆中声明的枚举类型
- 如何访问 VTK 的类枚举字段
- C++ 如何访问内部枚举类?
- 如何将枚举类写入文件并在C++中访问它?
- 访问向量字段的键 - 枚举类还是命名空间中的枚举?
- 枚举范围无法通过 C++ 中的类中的结构访问
- 为什么 clang 不允许通过实例访问嵌套枚举类?
- 通过进程模块C 枚举时,访问被拒绝
- 访问在C++类中声明的枚举
- 我的私有方法如何在C++中访问公共枚举
- C++中枚举访问语义背后的基本原理
- 不同类中的枚举访问
- 通过作用域和类型化枚举访问元组值失败
- 是否可以使用枚举访问数组