简体   繁体   中英

C++ calling a constructor with enum variable

There is a class definition as follows

class IOOptions
{
    public:
    IOOptions(int opt = 0) : _options(opt) { }
    \\ blah blah
    typedef enum { OPT1= 1, OPT2= 2} IOOopts;

    protected:
    int _options;
};

Now are the following two statements equivalent?

  • Statement 1: IOOptions io=IOOptions::OPT1;
  • Statement 2: IOOptions io=IOOptions(IOOptions::OPT1);

Yes, they are. The first statement winds up calling the constructor implicitly. The compiler will attempt to convert the enum value to an IOOptions object and will use the provided constructor to do so automatically, because the constructor is not marked explicit . (A one-arg non- explicit constructor can be used implicitly in conversions between types implicitly convertible to the constructor's argument type, and the type on which the constructor is declared.)

If you change your constructor to explicit IOOptions(int opt = 0) : _options(opt) { } then you will find that the first statement form no longer compiles, but the second form will continue to compile successfully.

Yes, both statements will have the same effect. But there is a third option which many people may find clearer:

IOOptions io(IOOptions::OPT1);

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