类成员初始化程序和初始化列表之间的冲突解决 [英] Conflict resolution between in-class member initializer and initialization list

查看:187
本文介绍了类成员初始化程序和初始化列表之间的冲突解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我先使用下面的代码:

Let me precede the question with the following code:

struct A
{
  explicit A(int i):a_{i} {}

  int a_
};

struct B
{
  B():mya_{5} {} // Initialize mya_ (again?)

  A mya_{7}; // Initialize mya_
};

struct B B mya _ mya _ c>的构造函数的初始化器列表。如何解决每个C ++标准, mya_.a _ 的最终值应该是 B 的结构是否完成?

In struct B we have a conflict between the in-class initializer for mya_ and mya_ being initialized in B's constructor's initializer list. How is this resolved per the C++ standard and what should the final value of mya_.a_ be when B's construction is complete?

推荐答案

初始化列表获胜。

例如,

struct B
{
  B():mya_{5} {}
  B(int) {}
  A mya_{7};
};

int main
{
  B b0;    // b.mya_.a_ is 5
  B b(42); // b.mya_.a_ is 7
}

12.6.2正在初始化基础和成员[class.base.init]

From 12.6.2 Initializing bases and members [class.base.init]


如果给定的非静态数据成员都有
brace-or-equal-initializer和mem初始化器,执行由mem初始化器指定的初始化
,并且忽略非静态数据
成员的括号或等于初始化器。 [示例:给定

If a given non-static data member has both a brace-or-equal-initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member’s brace-or-equal-initializer is ignored. [ Example: Given



struct A {
int i = /∗ some integer expression with side effects ∗/ ;
A(int arg) : i(arg) { }
// ...
};




A(int)构造函数将简单地将i初始化为arg,
,并且在i的括号或者等号初始化器中的副作用不会取
。 - end example]

the A(int) constructor will simply initialize i to the value of arg, and the side effects in i’s brace-or-equal- initializer will not take place. — end example ]

这篇关于类成员初始化程序和初始化列表之间的冲突解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆