冒号在构造函数中意味着什么?

lun*_*una 6 c++ syntax initialization ctor-initializer

可能的重复:
C++奇怪的构造函数语法
变量在构造函数中的冒号之后C++构造函数名后面的冒号(:)有
什么作用?

对于下面的C++函数:

cross(vector<int> &L_, vector<bool> &backref_, vector< vector<int> > &res_) : 

    L(L_), c(L.size(), 0), res(res_), backref(backref_) {

    run(0); 

}
Run Code Online (Sandbox Code Playgroud)

冒号(":")告诉左右两部分之间的关​​系是什么?可能,这段代码可以说什么呢?

Art*_*ger 5

这是一种在实际调用类的c'tor之前初始化类成员字段的方法.

假设你有:

class A {

  private:
        B b;
  public:
        A() {
          //Using b here means that B has to have default c'tor
          //and default c'tor of B being called
       }
}
Run Code Online (Sandbox Code Playgroud)

所以现在通过写作:

class A {

  private:
        B b;
  public:
        A( B _b): b(_b) {
          // Now copy c'tor of B is called, hence you initialize you
          // private field by copy of parameter _b
       }
}
Run Code Online (Sandbox Code Playgroud)