简体   繁体   English

在类中初始化向量

[英]initialize vector in class

I have the following problem. 我有以下问题。 I have a class, say 我有一堂课

class MyClass{
public:
  class MyNumber;
  MyClass(char const *filename);
  class MyNumber{
  public:
    MyNumber(int n) : n(n) {}
  private:
    int n;
  };

private:
  std::vector<MyNumber> mynumbers
};

Now I want to write a constructor for the class MyClass, which reads a file and depending on the content of the file initializes the vector mynumbers. 现在,我想为类MyClass编写一个构造函数,该构造函数读取一个文件,并根据文件的内容初始化向量mynumbers。 What I did is the following 我所做的是以下

MyClass::Myclass (char const * filename){
  int num = 0;
  std::string line;
  std::getline(file, line);              
  std::stringstream ss(line);              
  ss >> num; 
  mynumbers(num,MyNumber(5));

}

But I get the error "type 'std::vector' does not provide a call operator". 但是我收到错误消息“类型'std :: vector'不提供调用运算符”。 I also can't use a constructor initializer lists (at least I think so) since it depends on my input file how big my vector has to be. 我也不能使用构造函数初始化列表(至少我是这样认为的),因为它取决于我的输入文件矢量的大小。 Can somebody tell me how this is done? 有人可以告诉我这是怎么做的吗?

Just use the method assign 只需使用方法assign

mynumbers.assign(num,MyNumber(5));

As for this statement 至于这个说法

mynumbers(num,MyNumber(5));

then it corresponds to a call of a function operator. 那么它对应于函数运算符的调用。 However the standard class std::vector does not has such an operator. 但是标准类std::vector没有这样的运算符。 The object mynumbers in the constructor was already created/ So you can only assign it with new values. 构造函数中的对象mynumbers已创建/因此您只能为其分配新值。 You can not call its constructor a second time. 您不能再次调用其构造函数。 On the other hand the method assign is overloaded such away that it corresponds to the most of constructors of the class. 另一方面,方法assign被重载,以至于它对应于该类的大多数构造函数。

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

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