【问题标题】:Why is it okay to pass an enum as a function variable but not to return an enum?为什么可以将枚举作为函数变量传递但不能返回枚举?
【发布时间】:2012-01-26 20:40:50
【问题描述】:

我对我现在遇到的一个错误有点困惑。我班上有一个getter/setter。 setter 将枚举作为参数,getter 应返回此枚举。但是,我收到了 getter 的这个错误:

错误:C2143:语法错误:缺少';'在“会话::类型”之前

好像SessionType 未定义。但是我没有得到同样的二传手错误。有什么理由吗?有没有办法解决这个错误?

(顺便说一句,如果我返回 int,它编译得很好,但我宁愿让 getter 与 setter 保持一致)

这是我的代码:

Session.h

class Session {

public:

    enum SessionType {
        FreeStyle,
        TypeIn,
        MCQ
    };

    explicit Session();
    SessionType type() const;
    void setType(SessionType v);

private:

    SessionType type_;

}

Session.cpp:

SessionType Session::type() const { // ERROR!!
    return type_;
}

void Session::setType(SessionType v) { // No error?
    if (type_ == v) return;
    type_ = v;
}

【问题讨论】:

    标签: c++ class enums public


    【解决方案1】:

    改变

    SessionType Session::type() const { // ERROR!!
    

    Session::SessionType Session::type() const {
    

    【讨论】:

    • 澄清一下:SessionType是Session的成员,所以需要使用全限定类型名,即Session::SessionType。如果直接在类体内定义 type() ,则不必指定 Session::.
    【解决方案2】:

    你忘了关闭类声明:

    class Session {
    
    public:
    
        enum SessionType {
            FreeStyle,
            TypeIn,
            MCQ
        };
    
        explicit Session();
        SessionType type() const;
        void setType(SessionType v);
    
    private:
    
        SessionType type_;
    
    }; // <- semicolon here
    

    并且你需要在类外限定enum 名称:

    Session::SessionType
    

    【讨论】:

      【解决方案3】:

      问题是,当您在 Session.cpp 中定义函数时,在评估返回类型时,编译器还不太清楚它是类的成员函数,并且不知道在范围内有该枚举。它与函数的从左到右定义有关。试试这个

      Session::SessionType Session::type() const { // ERROR!!
          return type_;
      }
      

      注意,另一种情况有效,因为它在评估函数名称之前不会遇到枚举,因此枚举在范围内。

      此外,您遇到的错误是由于类定义末尾缺少分号。

      【讨论】:

        猜你喜欢
        • 2012-05-17
        • 2012-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多