考虑以下(简化的)情况:
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/