5

c++ 结构体初始化的问题

 2 years ago
source link: https://www.v2ex.com/t/846596
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

c++ 结构体初始化的问题

  iqoo · 42 分钟前 · 85 次点击

用的是 C++11 语法,如下代码:

struct Header {
  int x = 1;
  int y;
};

struct Packet {
  Header h;
};

Packet pkt = {
  .h = {
    .y = 2,
  },
};

int main(int argc, char *argv[]) {
  return 0;
}

报错: main.cc:11:8: error: no matching constructor for initialization of 'Header' .h = {

如果去掉 Header 结构体里的 = 1 倒是没问题,使用时自己赋值。不过这个字段是个固定的常量,所以想在定义的时候就设置好,每次使用的时候编译器自动填上这个字段,省的自己赋值。

不知是否有更好的办法。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK