结构中的函数 ? C++

Functions in Structures ? C++

我了解 C++ 中基本 struct 的工作原理,如本例所示:

struct Options 
{
   int num_particles;
   bool use_lbp;
   string infile;
   string outfile;
};

但是,我不明白下面的声明中有一个额外的部分。 Options():... 的目的是什么?

struct Options 
{
   Options()
      :num_particles(NUM_PARTICLES),
       use_lbp(false),
       infile(),
       outfile()
   {}

   int num_particles;
   bool use_lbp;
   string infile;
   string outfile;
};

这是否类似于下面代码中发生的事情?

struct State_
{
   State_( State pp ) : p( pp ) { }
   operator State() { return p; }
   State p;
};

Options() 是您的默认构造函数。结构和 类 在它们可以有方法和构造函数的意义上是等价的。 :之后是Options()的初始化列表。它告诉您在 Options():

的默认构造函数中
  • num_particles 初始化为 NUM_PARTICLES
  • ule_lbp 初始化为 false
  • infile初始化为空字符串
  • outfile 初始化为空字符串

类似的推理适用于 State_