[英]c++ - initializing an array member with aggregate initialization
With this code: 使用此代码:
struct Structure {
int a;
char b[4];
};
void function() {
int a = 3;
char b[] = {'a', 'b', 'c', 'd'};
}
Can I initialize Structure
with the values of a
and b
using aggregate initialization? 我可以使用聚合初始化使用a
和b
的值初始化Structure
吗?
I tried Structure{a, b}
, however that gives me the error cannot initialize an array element of type 'char' with an lvalue of type 'char [4]'
我尝试了Structure{a, b}
,但是这给了我错误cannot initialize an array element of type 'char' with an lvalue of type 'char [4]'
struct S {
int a;
char b[4];
};
int main() {
S s = { 1, {2,3,4,5} };
}
Edit: Just re-read your question - no, you can't do that. 编辑:重新阅读你的问题 - 不,你不能这样做。 You can't initialise an array with another array. 您无法使用其他阵列初始化数组。
If you are familiar with parameter-pack-expansion I think you can, like this: 如果您熟悉参数包扩展,我认为您可以这样:
struct Structure {
int a;
char b[4];
};
template< typename... I, typename... C>
void function(I... a, C... b) {
Structure s = { a..., b... }; // <- here -> a = 1 and b = 'a','b','c','d'
std::cout << s.a << '\n';
for( char chr : s.b ) std::cout << chr << ' ';
}
int main(){
function( 1, 'a','b','c','d' );
}
The output: 输出:
1
a b c d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.