c++ - 成员变量可以用来初始化初始化列表中的其他成员吗?

标签 c++ initialization-list member-variables

考虑以下(简化的)情况:

class Foo
{
private:
    int evenA;
    int evenB;
    int evenSum;
public:
    Foo(int a, int b) : evenA(a-(a%2)), evenB(b-(b%2)), evenSum(evenA+evenB)
    {
    }
};

当我像这样实例化 Foo 时:

Foo foo(1,3);

那么evenA为0,evenB为2,但是evenSum会被初始化为2吗?

我在我当前的平台 (iOS) 上尝试过,它似乎可以工作,但我不确定这段代码是否可移植。

感谢您的帮助!

最佳答案

这个定义明确且可移植,1但它可能容易出错。

成员按照它们在类主体中声明的顺序进行初始化,而不是它们在初始化列表中列出的顺序。因此,如果您更改类主体,此代码可能会静默失败(尽管许多编译器会发现这一点并发出警告)。


<子> 1。来自 C++ 标准中的 [class.base.init]:

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed.

(突出显示是我的。)

标准的这一部分接着给出一个使用成员变量来初始化其他成员变量的例子。

关于c++ - 成员变量可以用来初始化初始化列表中的其他成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720377/

相关文章:

c++ - `/path/to/uthash/utarray.h' 需要 CMake make[2] : *** No rule to make target `HelloTest' , 。停止

c++ - 从链接列表打印值,起始值作为函数中的默认值

c++ - 如何将数据插入到预先分配的 CSV 文件中?

c++ - 如何在 C++ 的基本成员初始化部分中初始化 std::map?

c++ - 初始化列表的好处

oop - 类成员变量不和全局变量一样糟糕吗?

c++ - 是否可以在未推导所有模板参数的情况下获取模板成员函数的函数指针?

c++ - 初始化列表需要其效果的初始化函数调用?

C++ : forbid a class to change the value pointed to by a pointer member variable

c++ - 将 C++ Lambda 存储在成员变量中以用作回调?