开发者

How do I declare the size of a string array if it's a member function

I have a pr开发者_StackOverflow社区oblem with setting the size of my array. In my code I have:

class Test {
    public:
       ....//Functions
    private:
      string name[];
};

Test() {
   //heres where i want to declare the size of the array
}

Is this possible?


No. But you could use a vector of strings instead:

private:
  std::vector<std::string> name;

Then in your constructor:

Test()
    : name(sizeOfTheArray)
{
}

The vector will be sized for the number of strings you specify. This means all memory for the strings will be allocated at once. You can change the size of the array as you wish, but there's nothing saying you have to. Thus, you get all the benefits of using a dynamically allocated array, and then some, without the drawbacks.


You will need to dynamically allocate memory for the array using new.

Declare the variable like this:

private:
    string* name;

And in your constructor do this:

int size = ...
name = new string[size];

And free the memory in the destructor like this:

delete [] name;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜