为了快速初始化小结构,我经常使用聚合初始化来保持代码的小和简单:
struct Foo {
int a;
int b;
int c;
};
Foo temp = {1, 2, 3};
我假设这还可以创建一个临时实例,该实例可以作为函数参数传递:
void myFunc(Foo foo) {
// ...
}
,这有可能吗?如何使用此特性的确切语法?
myFunc({1, 2, 3}); // ???
myFunc(Foo {1, 2, 3}); // ???
发布于 2017-04-28 02:13:00
第一种情况是复制列表初始化,对您的示例来说很好。
函数({ arg1,arg2,…});(7) 7)在函数调用表达式中,使用带括号的init-list作为参数,列表初始化初始化函数参数。
因此,对于myFunc({1, 2, 3});
,myFunc
需要一个Foo
;然后大括号内的列表{1, 2, 3}
将用于复制列表-初始化临时Foo
并作为参数传递给myFunc
。
对于myFunc(Foo {1, 2, 3});
,临时Foo
将显式地直接初始化列表,然后作为参数传递给myFunc
。
直接列表初始化和复制列表初始化之间有一些细微的区别,例如explicit
转换构造函数不考虑复制列表初始化:
struct Foo {
// explicit converting constructor
explicit Foo(int, int, int) {}
int a;
int b;
int c;
};
void myFunc(Foo foo) {
// ...
}
myFunc({1, 2, 3}); // fail, can't convert from braced-init-list to Foo
myFunc(Foo {1, 2, 3}); // fine
发布于 2017-04-28 02:07:08
这个小程序是为我编写的:
#include <iostream>
struct Foo {
int a;
int b;
int c;
};
void bar(const Foo&) {}
int main() {
bar({1,2,3});
bar(Foo{1,2,3});
}
第一个调用是隐式调用,第二个调用是显式调用;两者都有效。如果您有一个模板函数或一些不容易发生隐式转换的东西,那么您应该使用第二种形式。
发布于 2017-04-28 02:06:33
是的,你可以使用myFunc({1, 2, 3});
。
https://stackoverflow.com/questions/43677403
复制相似问题