如何在类中初始化 char 数组?

Sha*_*han 0 c++

我正要在类中初始化一个 char 数组:

class a{
    char a[25];
};

a::a(){
    a[] = {'a','b','c'};
}
Run Code Online (Sandbox Code Playgroud)

但给出编译时错误。

Ben*_*ley 5

如果您的编译器支持 C++11 功能,您可以这样做:

a::a() :arr({'a','b','c'})
{}
Run Code Online (Sandbox Code Playgroud)

否则,您必须手动执行此操作,或者您可以使用如下函数memcpy:

a::a() {
    memcpy(arr,"abc",3);
    // The other initialization method will fill the rest in with 0,
    // I don't know if that's important, but:
    std::fill(arr + 3, arr + 25, '\0');
}
Run Code Online (Sandbox Code Playgroud)

或者,正如 ephemient 所建议的:

a::a() {
    strncpy(arr, "abc", 25);
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种可能性:当 `strncpy` 可用时,它总是用 `\0` 填充 - `strncpy(a, "abc", 25)` 将写入 25 个字节,其中最后 22 个字节为 NUL。 (2认同)