简体   繁体   English

C ++使用枚举变量调用构造函数

[英]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; 语句1: IOOptions io=IOOptions::OPT1;
  • Statement 2: IOOptions io=IOOptions(IOOptions::OPT1); 声明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 . 编译器将尝试将枚举值转换为IOOptions对象,并将使用提供的构造函数自动执行此操作,因为该构造函数未标记为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.) (可以在可隐式转换为构造函数的参数类型的类型与声明构造函数的类型之间的转换中隐式使用单参数非explicit构造函数。)

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. 如果将构造函数更改为explicit IOOptions(int opt = 0) : _options(opt) { } ,则将发现第一个语句形式不再编译,但是第二个语句形式将继续成功编译。

Yes, both statements will have the same effect. 是的,这两个语句将具有相同的效果。 But there is a third option which many people may find clearer: 但是还有很多人可能会更清楚地发现的第三种选择:

IOOptions io(IOOptions::OPT1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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