我在程序中遇到错误。显然,我缺少有关语法的内容。下面的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
。