来自cppreference.com的C ++结构初始化

时间:2017-12-11 14:49:58

标签: c++ c++11

我试图编译下面的代码,但我总是提到错误:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char* Name;
    char* Branch;
} st_employee;

st_employee details[3] =
{
    [0].Name = "XXX",
    [0].Branch = "YYY",
    [1].Name = "ZZZ",
    [1].Branch = "PPP",
    [2].Name = "III",
    [2].Branch = "LLLL"
};

int main()
{
    printf("Hello world!");
    return 0;
}

编译:

c++ -x c -std=c11  -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors test.cpp -lm  -latomic  -Wmissing-field-initializers

错误:

test.cpp:44:5: warning: missing initializer for field 'Branch' of 'st_employee' [-Wmissing-field-initializers]
     [1].Name = "Chennai",
     ^
test.cpp:22:11: note: 'Branch' declared here
     char* Branch;
           ^
test.cpp:45:5: warning: missing initializer for field 'Branch' of 'st_employee' [-Wmissing-field-initializers]
     [2].Name = "Chennai"
     ^
test.cpp:22:11: note: 'Branch' declared here
     char* Branch;
           ^
test.cpp:46:1: warning: missing initializer for field 'Branch' of 'st_employee' [-Wmissing-field-initializers]
 };
 ^
test.cpp:22:11: note: 'Branch' declared here
     char* Branch;
           ^

如何解决错误?

3 个答案:

答案 0 :(得分:8)

您链接的代码是有效的C11,而不是C ++ 11。由于C和C ++是完全不同的语言,因此不能使用C ++编译器进行编译。

live example on wandbox.org

答案 1 :(得分:4)

在C ++ 11中,如果结构包含const char*&#39; s,您可以像这样初始化数组:

st_employee details[3] =
{
    {"XXX","YYY"},
    {"ZZZ","PPP"},
    {"III","LLLL"}
};

答案 2 :(得分:1)

除了其他答案之外,在C ++中你真的应该优先于原始字符指针/数组std::string和原始数组上的std::array容器。然后只需使用aggregate initialization初始化您的元素:

#include <iostream>
#include <string>
#include <array>

struct st_employee {
    std::string Name;
    std::string Branch;
};

int main() {
    std::array<st_employee, 3> details = { "XXX", "YYY", "ZZZ", "PPP", "III", "LLLL" };
    for (auto el : details) {
        std::cout << el.Name << ' ' << el.Branch << '\n';
    }
}