我有点困惑,我现在有一个错误。我的类中有一个getter/setter。setter接受一个enum作为参数,getter应该返回这个enum。然而,getter出现了这个错误:
错误:C2143:语法错误:在'Session::type'之前缺少';'
, if SessionType
未定义。但是setter没有得到同样的错误。有什么原因吗?有什么方法可以修复这个错误吗?
(顺便说一下,如果我返回一个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;
}
变化
SessionType Session::type() const { // ERROR!!
Session::SessionType Session::type() const {
问题是,当您在Session.cpp中定义函数时,在对返回类型进行评估时,编译器还没有完全意识到它是类的成员函数,并且在范围内没有该枚举。它与函数从左到右的定义有关。试试这个
Session::SessionType Session::type() const { // ERROR!!
return type_;
}
注意,另一种情况是有效的,因为它在对函数名求值之前不会遇到枚举,因此在作用域中有枚举。
同样,您得到的错误是由于在类定义的末尾缺少分号。
忘记关闭类声明:
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