c++ - 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};
}
这就是隐式构造函数的工作方式吗?或者这里还有其他东西在起作用?
解决方案
是的,这是它工作原理的一部分,但还有更多。可以显式的不仅仅是单参数构造函数。无论参数数量如何,您都可以为任何构造函数执行此操作,代码可以更好地解释:
#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
}
推荐阅读
- linux - 如何使用 unix 在具有重复行的 txt 文件中获取唯一值(行)?
- xml - 在树视图中为特定记录选择操作时如何调用函数
- c# - 如何检查空对象?
- ios - Google Vision API 可能存在内存泄漏
- android - Koin vs Kodein - 依赖注入你更喜欢什么?科特林
- javascript - 类型错误:context.getters.Function 不是 Vuex 的函数
- asp.net - 使用 ViewModel 时,对象不会从视图传递到控制器
- groovy - 如何在 Jmeter 中运行 shell 脚本 - Groovy
- android - 开放式回答问卷应用程序的片段或活动
- ios - UIPageViewController 中的 InputAccessoryView 默认不显示