枚举使用问题
Issue with Enum usage
我对枚举有问题(我猜它的用法):我已经在一个类中声明了一个枚举,我正在尝试在其子类中使用它。这里是(抽象的)超类:
//Function.h
class Function {
public:
enum FunctionType {
constant,
variable,
sum,
mul
};
...
virtual FunctionType getType();
};
这里是它的子类之一:
//Const.h
#include "Function.h"
#ifndef CONST_H_
#define CONST_H_
class Const:public Function {
....
public:
Const(double x);
....
Function::FunctionType getType();
....
~Const();
};
#endif /* CONST_H_ */
及其实施:
//Const.cpp
#include "Const.h"
#include "Function.h"
Function::FunctionType Const::getType(){
return Function::FunctionType::constant;
}
....
编译器引发以下错误:
error: ‘Function::FunctionType’ is not a class or namespace
return Function::FunctionType::constant;
^
我无法找出为什么我有这个错误,以及这个对我来说听起来简单合理的代码有什么问题(当然不是)。
若要限定枚举值,请不要使用枚举类型名称:
enum enum_t { ENUM_VALUE };
auto e = ENUM_VALUE; // no enum_t::
在您的情况下,解决方案是:
struct Function {
enum FunctionType {
constant
};
virtual FunctionType getType();
};
struct Const : Function {
Function::FunctionType getType() { return Function::constant; }
};
Function::FunctionType::constant
是一个错误的事实来自枚举是声明常量的 C 功能。从枚举的 cppreference.com 页面,可以读取:
无作用域枚举
enum name { enumerator = constexpr , enumerator = constexpr , ... }
(1)
1) 声明一个基础类型不固定的无作用域枚举类型(在这种情况下,基础类型为 int,或者,如果不是所有枚举器值都可以表示为 int,则为可以表示所有枚举器值的实现定义的较大整数类型。如果枚举器列表为空,则基础类型就像枚举具有值为 0 的单个枚举器一样)。
如果要使用强类型的作用域枚举,请参阅@Angrew答案和enum class
。
@YSC的答案在解释你得到的错误时是100%正确的。
为了添加更广泛的上下文,从 C++11 开始,以作用域枚举的形式支持您最初打算使用的语法。在这些枚举中,整数之间的隐式转换不可用,并且枚举器的名称在枚举范围内。它们由语法enum class
引入。
这与无作用域枚举(仅使用 enum
获得的枚举)形成对比,其中不存在这样的范围规则。枚举名称根本不引入作用域,因此在作用域解析运算符::
的左侧使用它是一个错误。
可以在代码中使用作用域枚举,如下所示:
class Function {
public:
enum class FunctionType {
constant,
variable,
sum,
mul
};
...
virtual FunctionType getType();
};
Function::FunctionType Const::getType(){
return Function::FunctionType::constant;
}
注意,在派生自Function
的类中,限定FunctionType::constant
为Function::FunctionType::constant
是不必要的;对从Function
继承的所有成员的访问是隐式的。
尝试:
return Function::constant;
而不是:
return Function::FunctionType::constant;
- C++关于ENUM的问题。我得到的响应比枚举列表大
- Visual Studio 2017 生成工具与枚举类型的问题
- `enable_if`带有``枚举模板专业化问题''
- 将此枚举传递给 CTOR 有什么问题?
- 解决枚举命名问题 - Qt
- 设计问题:枚举或函数或其他什么
- 对象、枚举类型和范围的问题
- 枚举使用问题
- 全局变量和枚举之间的作用域问题
- c++枚举问题和c++中可能的循环依赖
- 枚举类的vector的初始化列表存在问题
- 枚举初始化问题
- 枚举的元编程问题
- 枚举问题,还是我的理解
- 使用枚举向向量添加的问题
- C++0x枚举类的Emacs cc模式缩进问题
- 枚举进程句柄,奇怪的问题
- 枚举窗口时出现问题
- 类型定义枚举的问题.以及Visual Studio 2005中的错误
- 枚举的命名空间问题