简体   繁体   中英

Overloading the () operator for an enum in a class - C++

I came across the following piece of code :-

class MyClass{

public:

    enum ITEMS {

        ZERO = 0,
        ONE,
        TWO,
        THREE

    };

    enum ITEMS item;
    MyClass():item(THREE){}
    MyClass(ITEMS item):item(item){};
    operator ITEMS () {
        return item;
    }

};

I am unable to figure out what the operator() overloading on the enum ITEMS does . How would that be used in the context of objects of type MyClass ? Suppose we have an object :-

MyClass obj1;

Can we do obj1.VALUES() ? I am getting compilation errors if I try that.

operator ITEMS (){...} is a cast overload for target type ITEMS . When you cast an instance of MyClass to type MyClass::ITEMS , class member item gets returned.

It allows you do make a conversion from object of type MyClass to variable of type ITEMS , example:

MyClass mm;
MyClass::ITEMS it = mm;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM