如何在同一构造函数中使用构造函数参数

How to use a constructor parameter within the same constructor?

本文关键字:构造函数 参数      更新时间:2023-10-16

我想使用一个构造函数参数some_function作为参数的默认初始化一些其他的构造函数参数,即some_other_function:

SomeConstructor(SomeFunction some_function,
                SomeOtherFunction some_other_function = SomeOtherFunction(some_function)) :
      some_function_(some_function),
      some_other_function_(some_other_function) 
{...}

不幸的是,这会导致编译错误:

error: 'some_function' was not declared in this scope

不用语法糖(*):

Constructor (A a, B b)
  : a_(a), b_(b) {
  // ...
}
Constructor (A a)
  : Constructor (a, B(a)) {}

虽然这只在c++ 11以后起作用,但该特性被称为委托转发构造函数。


(*)"语法糖"在这里并不是真正正确的术语,因为它在语义上并不等同于带有默认实参的构造函数。(据我所知,默认参数是在调用现场作为"正常"参数插入的。)