当我们不应该在构造函数中使用初始化列表时,有人可以引用示例代码吗?如何通过赋值来克服这个问题?
我正在寻找以下语句的示例
This might happen when your class has two constructors that need to initialize the
this
object's data members in different orders. Or it might happen when two data members are self-referential. Or when a data-member needs a reference to the this object, and you want to avoid a compiler warning about using the this keyword prior to the { that begins the constructor's body (when your particular compiler happens to issue that particular warning). Or when you need to do an if/throw test on a variable (parameter, global, etc.) prior to using that variable to initialize one of your this members.
最佳答案
我相信您的声明的作者所指的主要概念是对初始化列表中变量的调用不是您在初始化列表中看到它们的顺序,但是按照变量在类定义中列出的顺序。
这意味着
- 如果您有两个使用初始化列表的不同构造函数,它们必须以相同的顺序初始化它们
- 您对排序的控制(如果您有相互依赖的成员,这可能很重要)是有限的
我建议您阅读 Scott Meyer 的 Effective C++
,其中涵盖了这一点(以及许多其他有用且信息丰富的主题)。
关于c++ - 我们什么时候不应该在构造函数中使用初始化列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323739/