为什么可以将枚举作为函数变量传递,但不能返回枚举?
Why is it okay to pass an enum as a function variable but not to return an enum?
我有点困惑,我现在有一个错误。我的类中有一个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
相关文章:
- 是否可以将函数导入命名空间,但不能导出它?
- std::unique_ptr 在 GCC 中工作,但不能在 Visual Studio 中编译
- 声明C++具有动态大小的数组类型在 Linux 中工作正常,但不能在 Windows 中工作
- 枚举窗口不检测窗口
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- std::chrono::d uration 可以按秒初始化,但不能按毫秒初始化?
- Python/C++:可以导入犰狳(arma::)但不能导入子程序arma::arma_rng::randn
- 为什么我可以从C++文件中读取 int 值,但不能浮点?
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- SqLite c++,可以创建数据库,但不能将 anthing 插入到表中
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 16 位系统中的程序如何访问大于 65535 的整数,但不能访问地址
- C++:返回本地对象,但不能正常工作
- 在 C++ 中使用枚举而不是结构进行标记调度
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- C ++枚举可以与整数进行比较,但不能从整数分配?
- c++中的枚举类不能在Mac中编译,而在Windows中工作
- 枚举类型不能接受 CIN 命令
- 为什么可以将枚举作为函数变量传递,但不能返回枚举?
- C++将浮点值强制转换为枚举,但不能使用VS 2010