简体   繁体   English

C++ 隐式构造如何工作,结构初始化?

[英]C++ How does implicit construction work, struct initialization?

I have a question about implicit constructors.我有一个关于隐式构造函数的问题。 So let's say I have the following scenario:所以假设我有以下场景:


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

struct MyStruct2 {
    MyStruct1 myStruct1;
};

Now what I want to know is if 1 and 2 are equivalent below:现在我想知道的是下面的 1 和 2 是否等价:

1) 1)

int main() {

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

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

Is that how implicit constructors works?这就是隐式构造函数的工作方式吗? Or is there something else at play here?或者这里还有其他东西在起作用?

Yes, that is part of how it works, but there is more to it.是的,这是它工作原理的一部分,但还有更多。 It isn't only one-parameter constructors that can be explicit.可以显式的不仅仅是单参数构造函数。 You can do it for any constructor regardless of number of parameters, better explained by code:无论参数数量如何,您都可以为任何构造函数执行此操作,代码可以更好地解释:

#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
}

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

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