如何在同一构造函数中使用构造函数参数
How to use a constructor parameter within the same constructor?
我想使用一个构造函数参数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以后起作用,但该特性被称为委托或转发构造函数。
(*)"语法糖"在这里并不是真正正确的术语,因为它在语义上并不等同于带有默认实参的构造函数。(据我所知,默认参数是在调用现场作为"正常"参数插入的。)
相关文章:
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在按值调用 (c++) 中转发构造函数参数
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 如何在构造函数参数中初始化"std::set"?
- 何时应在构造函数参数中使用 const C++?
- 使用模板化结构作为构造函数参数
- 使用 lambda 作为构造函数参数是否需要C++ 17?
- 如何使输入文本文件成为构造函数参数?c++
- shared_ptr构造函数参数是否应按值传递
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 复制构造函数参数为0
- 用作成员构造函数参数的函数的求值顺序
- 结构中的默认成员值或默认构造函数参数
- C++将引用成员绑定到构造函数参数
- 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?
- 模板函数指针参数与构造函数参数
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 如何基于构造函数参数模板化类成员函数的代码
- 将派生类构造函数参数传递给受保护的成员
- 如何根据构造函数参数使用超类类型初始化成员变量?