我需要一个定义为类属性的 char * 数组,并在类的构造函数中使用长度对其进行初始化。例如:
Foo.h:
class Foo{
public:
char * array[1] // declare the array here, syntax unsure
Foo(int length);
}
Foo.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*
.您甚至可以使用 the other 之一有用的构造函数。特别是如果你想定义 length
元素的拷贝 x
你可以使用:
array(length, x)
然后,您最终可以使用 push_back
将它们推送进来/emplace_back
.
一些小改动
如果char*
在语义上是一个字符串,那么你应该使用 std::vector<std::string>
.
如果类如您描述的那样是最小的,那么您可以简单地使用:
using Foo = std::vector<std::string>;
类型别名不会创建新类型,它只会创建一个新的类型别名。
关于C++ - 在构造函数中初始化指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27370165/