I need an array of char * defined in as a class's attribute, and initialize it with a length inside the class's constructor. For example:
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
}
Not sure about the syntax...I've only seen declaration of array of pointers with a length. I wonder how to declare it first and set/redeclare a new length later.
Use an std::vector
:
class Foo{
public:
std::vector<char*> array;
Foo(int length) : array(length) {}
}
In:
array(length)
you will construct a container with length
default constructed char*
. You can even use one of the other useful constructors. Specifically if you want to define length
copies of the element x
you can use:
array(length, x)
You can then, eventually, push them in with push_back
/ emplace_back
.
If char*
is semantically a string, then you should use std::vector<std::string>
.
And if the class is minimal as you described it, then you can simply use:
using Foo = std::vector<std::string>;
The type alias won't create a new type, it will only create a new type alias .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.