C++ - 初始化构造函数中的指针数组

C++ - Initialize array of pointers within a constructor

本文关键字:指针 数组 构造函数 初始化 C++      更新时间:2023-10-16

我需要在 中定义为类属性的 char * 数组,并使用类构造函数中的长度对其进行初始化。例如:

class Foo{
    public:
        char * array[1]    // declare the array here, syntax unsure
        Foo(int length);
}

福.cpp:

Foo::Foo(int length){
    array[length]      // set the length of the array here, syntax unsure
}

不确定语法...我只见过带有长度的指针数组的声明。我想知道如何先声明它,然后再设置/重新声明新的长度。

如何使用动态数组

使用std::vector

class Foo{
public:
    std::vector<char*> array;
    Foo(int length) : array(length) {}
}

在:

array(length) 

您将使用默认构造length char*构造一个容器。您甚至可以使用其他有用的构造函数之一。具体而言,如果要定义元素length副本x可以使用:

array(length, x)

然后,您最终可以使用push_back/emplace_back将它们推入。

一些小细节

如果char*在语义上是一个字符串,那么你应该使用 std::vector<std::string> .

如果类如您所描述的那样最小,那么您可以简单地使用:

using Foo = std::vector<std::string>;
类型别名

不会创建新类型,它只会创建新的类型别名