简体   繁体   English

C ++结构字段的顺序在聚合初始化中是否重要

[英]Does the order of C++ struct fields matter in aggregate initialization

Is the following code produce defined behavior or undefined behavior. 以下代码是产生定义的行为还是未定义的行为。 I tried it on my VC++ and I got one thing, but I'm curious to see if that is just coincendence or if it is mandated by the c++ standard. 我在VC ++上尝试了一下,但得到了一件事,但我很想知道这仅仅是巧合还是由c ++标准强制执行。

#include <iostream>
class TestClass {
public:
    char testChar;
    double testDouble;
    int testInt;
};

int main(int argc, char** argv) {
    TestClass s = {412.1, 52};
    std::cout << s.testChar + s.testDouble + s.testInt << std::endl;
}

The behavior is defined, but the result might not be what you expect. 行为已定义,但结果可能不是您期望的。

The order of the fields is important. 字段的顺序很重要。 For aggregate initialization each value will initialize the next member in order of declaration, so in the code above, testChar will get the value static_cast<char>(412.1) , testDouble will get value 52 and testInt will get value 0 (the standard guarantees that all members for which no value is provided will be initialized to 0. 对于聚合初始化,每个值将按照声明的顺序初始化下一个成员,因此在上面的代码中, testChar将获得值static_cast<char>(412.1)testDouble将获得值52testInt将获得值0 (标准保证没有提供任何值的所有成员都将初始化为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM