Sam*_*Sam 3 c++ enums identifier
我对Enum有一个问题(我想它的用法):我在一个类中声明了一个Enum,我试图在它的子类中使用它.这里是(抽象)超类:
//Function.h
class Function {
public:
enum FunctionType {
constant,
variable,
sum,
mul
};
...
virtual FunctionType getType();
};
Run Code Online (Sandbox Code Playgroud)
这里有一个子类:
//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_ */
Run Code Online (Sandbox Code Playgroud)
及其实施:
//Const.cpp
#include "Const.h"
#include "Function.h"
Function::FunctionType Const::getType(){
return Function::FunctionType::constant;
}
....
Run Code Online (Sandbox Code Playgroud)
编译器抛出以下错误:
error: ‘Function::FunctionType’ is not a class or namespace
return Function::FunctionType::constant;
^
Run Code Online (Sandbox Code Playgroud)
我无法找出为什么我有这个错误,这个代码听起来容易和声音有什么问题(当然不是).
要限定枚举值,请不要使用枚举类型名称:
enum enum_t { ENUM_VALUE };
auto e = ENUM_VALUE; // no enum_t::
Run Code Online (Sandbox Code Playgroud)
在您的情况下,解决方案是:
struct Function {
enum FunctionType {
constant
};
virtual FunctionType getType();
};
struct Const : Function {
Function::FunctionType getType() { return Function::constant; }
};
Run Code Online (Sandbox Code Playgroud)
这Function::FunctionType::constant
是一个错误的事实来自枚举是一个C函数来声明常量.从enum上的cppreference.com页面可以看到:
无范围的枚举
enum name { enumerator = constexpr , enumerator = constexpr , ... }
(1)
1)声明一个未固定的枚举类型,其底层类型不固定(在这种情况下,底层类型是int或者,如果不是所有枚举器值都可以表示为int,则可以表示实现定义的更大的整数类型所有枚举器值.如果枚举器列表为空,则基础类型就好像枚举具有值为0的单个枚举器.
如果要使用强类型的作用域枚举,请参阅@Angrew answer和enum class
.