成员初始化程序的顺序 [英] Order of member initializers

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

问题描述

以下代码给出正确的输出,如果我声明变量ij,就像int i, j;

class A 
{
  int i, j;

public:
    A(int val) : i(val), j(i + 1)
    {
        cout<<i<<endl<<j<<endl;
    }
};

但是如果我声明变量ij,如int j, i;.然后j打印垃圾值.

class A 
{
  int j, i;

public:
    A(int val) : i(val), j(i + 1)
    {
        cout<<i<<endl<<j<<endl;
    }
};

那么,这取决于变量声明的顺序吗?

解决方案

它取决于变量声明的顺序吗?

是的,数据成员总是按照其声明顺序进行初始化,这与成员初始值设定项列表的顺序无关.

这意味着对于您的第二个代码段,j总是在i之前初始化;但是,当它由成员初始值设定项i初始化时,仍未初始化.

对象的完整初始化顺序为:

(重点是我的)

列表中成员初始值设定项的顺序无关紧要:实际 初始化顺序如下:

1)如果构造函数用于派生最多的类,则虚拟基数 类按照它们出现的顺序进行初始化 基类声明的深度优先从左到右遍历 (从左到右是指基本说明符列表中的外观)

2)然后,直接基类按从左到右的顺序初始化为 它们出现在此类的基本说明符列表中

3)然后,按以下顺序初始化非静态数据成员: 类定义中的声明.

4)最后,执行构造函数的主体

Following code gives correct output, If I declare variables i and j, Like int i, j;

class A 
{
  int i, j;

public:
    A(int val) : i(val), j(i + 1)
    {
        cout<<i<<endl<<j<<endl;
    }
};

But If I declare variable i and j, like int j, i;. then j print garbage value.

class A 
{
  int j, i;

public:
    A(int val) : i(val), j(i + 1)
    {
        cout<<i<<endl<<j<<endl;
    }
};

So, Is it depend on order of declaration of variables?

解决方案

Is it depend on order of declaration of variables?

Yes, the data members are always initialized in the order of their declarations, which has nothing to do with the order of the member initializer lists.

That means for your 2nd code snippet, j is always initialized before i; but when it's initialized by member initializer i is still not initialized.

The complete initialization order for the object is:

(emphasis mine)

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed

这篇关于成员初始化程序的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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