c++ - 如何在类中初始化空终止字符数组

标签 c++ arrays class char

我想知道除了使用 for 循环之外,是否还有其他方法可以在类构造函数中用 null 终止符填充 char 数组。使用 for 循环它工作正常。但我认为应该有更简单的方法......或者我错了?

String::String()
{
  for (int i = 0; i < 80; i++)
       stringNew[i] = '\0';
}

最佳答案

如果stringNew 是一个std::string,你可以调用constructor :

//Initializes 'stringNew' with 80 times '\0'
String::String() : stringNew(80, '\0') {}

如果它是一个char[],你可以调用std::fill :

String::String()
{
    std::fill(std::begin(stringNew), std::end(stringNew), '\0');
}

您也可以使用循环,就像在您的示例中一样。

关于c++ - 如何在类中初始化空终止字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768429/

相关文章:

javascript - 使用 Space 值从 JSON 中过滤数组

css - 如何使用另一个 CSS 类覆盖 CSS 类的属性

c++ - 来自类的访问列表,在父类中

C++ 子类继承父类构造函数

objective-c - 二维数组的 C 内存管理

c++ - 如何自动将ID属性分配给C++中的类对象

python - 检查列表中项目的交集

javascript - 如何更改 Javascript 中的类变量?

c++ - 从函数隐式转换为函数指针?

c++ - 澄清 : What makes 'new' an operator in C++