1

有了这个代码阵列成员:C++ - 初始化与骨料初始化

struct Structure { 
    int a; 
    char b[4]; 
}; 

void function() { 
    int a = 3; 
    char b[] = {'a', 'b', 'c', 'd'}; 
} 

可使用集合初始化我初始化Structurea值和b
我试过Structure{a, b},然而,让我的错误cannot initialize an array element of type 'char' with an lvalue of type 'char [4]'

+0

如果更改'炭B []'通过'std :: array ',是的。 [演示](http://coliru.stacked-crooked.com/a/8ac7cfe90b9a75e0) – Jarod42

回答

0
struct S { 
    int a; 
    char b[4]; 
}; 

int main() { 
    S s = { 1, {2,3,4,5} }; 
} 

编辑:刚才重读你的问题 - 不,你不能这样做。你不能用另一个数组初始化一个数组。

0

如果您熟悉参数包膨胀我觉得还可以,像这样:

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'); 
} 

输出:

1 
a b c d