简体   繁体   English

在C ++中初始化构造函数初始化列表中的char数组

[英]Initialize array of char in initialization list of constructor in C++

Is it ok to use initialization like this? 可以像这样使用初始化吗?

class Foo
{
public:
   Foo() : str("str") {}
   char str[4];
};

And this? 还有这个?

int main()
{
   char str[4]("str");
}

Both give me an error in gcc 4.7.2: 两者都给我gcc 4.7.2中的错误:

error: array used as initializer error:用作初始化程序的数组

Comeau compiles both. Comeau编译两者。

This code is valid C++03 and gcc is simply not conformant here. 这段代码是有效的C ++ 03,gcc在这里根本不符合。

The language that allows this syntax for initializing character arrays is the same as allows it for any other type; 允许此语法初始化字符数组的语言与允许任何其他类型的语言相同; there are no exceptions that would prohibit it from being used on character arrays. 没有例外会禁止它在字符数组上使用。 () and = initialization are equivalent in these cases and the character array should simply be initialized according to 8.5.2. ()=初始化在这些情况下是等效的,字符数组应该根据8.5.2进行初始化。

Here's a confirmed gcc bug report that covers this. 这是一个确认的gcc错误报告,涵盖了这一点。

In C++03, the non-static member array cannot be initialized as you mentioned. 在C ++ 03中,无法按照您的提及初始化非静态成员数组。 In g++ may be you can have an extension of initializer list , but that's a C++11 feature. 在g ++中你可以拥有初始化列表的扩展,但这是一个C ++ 11特性。

Local variable in a function can be initialized like this: 函数中的局部变量可以像这样初始化:

char str[] = "str"; // (1)
char str[] = {'s','t','r',0}; // (2)

Though you can mention the dimension as 4 , but it's better not mentioned to avoid accidental array out of bounds. 虽然你可以提到维度为4 ,但最好不要提及以避免意外数组越界。

I would recommend to use std::string in both the cases. 我建议在两种情况下都使用std::string

In C++03, that is not possible. 在C ++ 03中,这是不可能的。 Comeau might compile it because of non-Standard extension. 由于非标准扩展,Comeau可能会编译它。

In C++11, you can do this: 在C ++ 11中,您可以这样做:

Foo() : str({'s','t','r'}) {}       //C++11 only

Or, you may prefer this intead: 或者,您可能更喜欢这个内容:

class Foo
{
public:
   Foo() {}
   char str[4] = "str"; //in-class initialization (C++11 only)
};

Also, you might consider using std::string or std::vector<char> irrespective of the version of C++ you're using. 此外,您可以考虑使用std::stringstd::vector<char>而不管您正在使用的C ++版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM