简体   繁体   English

C ++在类初始化时设置数组数据成员的大小

[英]C++ Set size of an array data member at initialization of class

I need to make a class that has an array as a data member. 我需要创建一个具有数组作为数据成员的类。 However I would like to make it so that the user can choose the size of the array when an object of that class is created. 但是,我想这样做,以便用户可以在创建该类的对象时选择数组的大小。 This doesn't work: 这不起作用:

class CharacterSequence {

private:

  static int size;
  char sequence[size];

public:

  CharacterSequence(int s) {
    size = s;
  }

};

How would I do this? 我该怎么做?

Use a std::vector : 使用std::vector

class CharacterSequence
{
private:
    std::vector<char> _sequence;

public:
    CharacterSequence(int size) : _sequence(size)
    {
    }
}; // eo class CharacterSequence

You can't. 你不能 Variable length arrays are not supported by C++. C ++不支持可变长度数组。

Why not use a std::vector<char> instead? 为什么不使用std::vector<char>代替呢? Its size can be set on construction. 它的大小可以在结构上设置。

Others have suggested using a std::vector... but I don't think that's what you really want. 其他人建议使用std :: vector ...,但我认为这不是您真正想要的。 I think you want a template: 我认为您想要一个模板:

template <int Size>
class CharacterSequence {

private:

  char sequence[Size];

public:

  CharacterSequence() {
  }
};

You can then instantiate it to whatever size you want, such as: 然后,您可以将其实例化为任意大小,例如:

CharacterSequence<50> my_sequence;

Determining the size of an array during run time is nothing but allocating memory at run time. 确定运行时阵列的大小无非是在运行时分配内存。 But size of the array has to be determined during compile time. 但是必须在编译时确定数组的大小。 Hence you cannot follow the method you mentioned above. 因此,您不能遵循上面提到的方法。

Alternatively, you can create a pointer and allocate memory at run time ie you can assign the size of your wish when you create object as below: 另外,您可以创建一个指针并在运行时分配内存,即,您可以在创建对象时分配所需的大小,如下所示:

class CharacterSequence {

private:

  static int size;
  char *sequence;

public:

  CharacterSequence(int s) {
    size = s;
    sequence = new char[size];
  }
  ~CharacterSequence(){
      delete []sequence;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM