C++ - 初始化构造函数中的指针数组
C++ - Initialize array of pointers within a constructor
我需要在 中定义为类属性的 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>;
类型别名不会创建新类型,它只会创建新的类型别名。
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空