gpt4 book ai didi

C++:在类内、类外应用枚举

转载 作者:行者123 更新时间:2023-11-28 01:39:00 25 4
gpt4 key购买 nike

class Stepper {
public:
enum microstepping {
FULL,
HALF,
QUARTER
};
int stepsPerStep;

Stepper(microstepping _microstepping) {
switch(_microstepping){
case FULL:
stepsPerStep = 1;
break;
case HALF:
stepsPerStep = 2;
break;
case QUARTER:
stepsPerStep = 4;
break;
}
}

};

void main() {
Stepper stepperA(FULL);//Problem shows here

}

/*我正在尝试使用枚举在类的特定实例中设置内部变量。问题是当我尝试使用它时,枚举在类外无法识别。在类外声明枚举不是一种选择。*/

最佳答案

您需要使用 Stepper 范围对其进行限定 -

class Stepper {
public:
enum microstepping {
FULL,
HALF,
QUARTER
};
int stepsPerStep;

Stepper(microstepping _microstepping) {
switch(_microstepping){
case FULL:
stepsPerStep = 1;
break;
case HALF:
stepsPerStep = 2;
break;
case QUARTER:
stepsPerStep = 4;
break;
}
}

};

int main() {
Stepper stepperA(Stepper::FULL);
}

并尽可能使用enum class -

class Stepper {
public:
enum class microstepping {
FULL,
HALF,
QUARTER
};
int stepsPerStep;

Stepper(microstepping _microstepping) {
switch(_microstepping){
case microstepping::FULL:
stepsPerStep = 1;
break;
case microstepping::HALF:
stepsPerStep = 2;
break;
case microstepping::QUARTER:
stepsPerStep = 4;
break;
}
}

};

int main() {
Stepper stepperA(Stepper::microstepping::FULL);
}

关于C++:在类内、类外应用枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com