Explicit constructor taking multiple arguments

前端 未结 4 1118
面向向阳花
面向向阳花 2021-01-30 03:36

Does making a constructor having multiple arguments explicit have any (useful) effect?

Example:

class A {
    public:
        explicit A( in         


        
4条回答
  •  孤城傲影
    2021-01-30 04:21

    Here's my five cents to this discussion:

    struct Foo {
        Foo(int, double) {}
    };
    
    struct Bar {
        explicit Bar(int, double) {}
    };
    
    void foo(const Foo&) {}
    void bar(const Bar&) {}
    
    int main(int argc, char * argv[]) {
        foo({ 42, 42.42 }); // valid
        bar({ 42, 42.42 }); // invalid
        return 0;
    }
    

    As you can easily see, explicit prevents from using initializer list alongside with bar function bacause the constructor of struct Bar is declared as explicit.

提交回复
热议问题