Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return enum from member function

Tags:

c++

enums

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;} }
like image 786
Yakov Avatar asked Nov 30 '25 10:11

Yakov


1 Answers

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.

like image 129
Xeo Avatar answered Dec 02 '25 22:12

Xeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!