从成员函数返回枚举 [英] Return enum from member function
问题描述
我想要返回枚举的补充函数:
class myClass {
private:
res _res;
public:
enum res {ok,fail};
res getRes()
bool checkRes(res r);
//更改_res值的其他函数
}
此实现生成编译错误:
res myClass :: getRes(){return _res;}
/ pre>
但是下面是可以的:
myClass :: res myClass :: getRes(){return _res;}
为什么要由范围指定枚举返回类型
,而作为参数类型范围的枚举不是必需的 - 以下工作可以:bool myClass :: checkRes(res r){
if(_res == r){retun true;}
else {return false;}}
解决方案因为返回类型不在类的词法范围内。如果你有支持C ++ 11的编译器,使用尾随的返回类型(也称为后指定的返回类型):
auto myClass :: getRest() - > res {return _res; }
- >
实际上,即使是参数列表)已经属于类的词汇范围,因此没有资格是必要的。I want to mplement function that returns enum:
class myClass{ private: res _res; public: enum res{ok,fail}; res getRes() bool checkRes(res r); //other function that change _res value }
This implementation generates compilation error:
res myClass::getRes(){return _res;}
But the following is OK:
myClass::res myClass::getRes(){return _res;}
Why enum return type should be specified by scope ,while as an argument type scope for enum is not necessary - the following works OK:
bool myClass::checkRes(res r){ if (_res == r){retun true;} else {return false;} }
解决方案Because the return type is not in the lexical scope of the class. If you have a C++11 aware compiler that supports it, use the trailing return type (also called late-specified return type):
auto myClass::getRest() -> res{ return _res; }
The part after
->
(infact, even the paramter list) already belongs to the lexical scope of the class, as such no qualifications are necessary.这篇关于从成员函数返回枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!