枚举使用问题

Issue with Enum usage

本文关键字:问题 枚举      更新时间:2023-10-16

我对枚举有问题(我猜它的用法):我已经在一个类中声明了一个枚举,我正在尝试在其子类中使用它。这里是(抽象的)超类:

//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::constantFunction::FunctionType::constant是不必要的;对从Function继承的所有成员的访问是隐式的。

尝试:

return Function::constant;

而不是:

return Function::FunctionType::constant;