我想使用构造函数参数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)
{...}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这给出了一个编译错误:
error: 'some_function' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
只是在没有语法糖(*)的情况下这样做:
Constructor (A a, B b)
: a_(a), b_(b) {
// ...
}
Constructor (A a)
: Constructor (a, B(a)) {}
Run Code Online (Sandbox Code Playgroud)
虽然这仅适用于C++ 11,但该功能称为委托或转发构造函数.
(*)"syntactic sugar"在这里并不是正确的术语,因为它在语义上不等同于带有默认参数的构造函数.(默认参数是 - 据我所知 - 在呼叫站点插入"普通"参数.)