首页 > 解决方案 > C++ 隐式构造如何工作,结构初始化?

问题描述

我有一个关于隐式构造函数的问题。所以假设我有以下场景:


struct MyStruct1 {
    bool myBool1 = false;
    bool myBool2 = false;
    MyStruct1() = default;
    MyStruct1(bool val)
        : myBool1(val)
        , myBool2(val)
    {}
};

struct MyStruct2 {
    MyStruct1 myStruct1;
};

现在我想知道的是下面的 1 和 2 是否等价:

1)

int main() {

    MyStruct2 myStruct2;
    myStruct2.myStruct1 = true;
}
int main() {

    MyStruct2 myStruct2;
    myStruct2.myStruct1 = MyStruct1{true};
}

这就是隐式构造函数的工作方式吗?或者这里还有其他东西在起作用?

标签: c++constructorimplicit-conversion

解决方案


是的,这是它工作原理的一部分,但还有更多。可以显式的不仅仅是单参数构造函数。无论参数数量如何,您都可以为任何构造函数执行此操作,代码可以更好地解释:

#include <memory>

struct MyStruct1 {
    bool myBool1 = false;
    bool myBool2 = false;
    
    explicit MyStruct1(bool val1 = false, bool val2 = false)
        : myBool1(val1)
        , myBool2(val2)
    {}

};

void func (const MyStruct1& myStruct = {}) // This fails if constructor is explicit
{
    // do something with struct
}

MyStruct1 func2 (bool a)
{
    if (!a) {
        return {}; // Returning default like this fails if constructor is explicit
    } 
    return {true, false}; // Fails if constructor is explicit
}

int main()
{
    auto msp = std::make_unique<MyStruct1>(true, false); // Perfect forwarding is always OK

    func({true, false});            // Fails to compile if constructor is explicit
    func(MyStruct1{true, false});   // Always OK
    MyStruct1 ms1 = {true, false};  // Fails to compile if constructor is explicit
    MyStruct1 ms2{true, false};     // Always OK
    MyStruct1 ms3 = {};             // Fails if constructor is explicit
}

推荐阅读