簡體   English   中英

初始化具有其他結構和數組的C ++結構的正確方法

[英]Proper way to Initialize C++ struct that has other structs and array

我有以下代碼,我需要初始化XYZ結構。 請給我一種方法。

struct Demo
{
    int abc[10];
    int reply_port;
};

struct XYZ 
{
    struct Demo dem[10];
    int x;
    int y;
    struct Demo a;
    struct Demo b;
    struct Demo c;
} arr[100];

Demo1是另一個在其他文件中可用的struct 請告訴我有關如何初始化XYZ結構的有效方法。

謝謝

我不知道您為什么要這樣做,但是如果您堅持:

  struct XYZ myXYZ = { 
    {   
      // dem[10]
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80},
      {{1,2,3,4,5,6,7,8,9,10},80}
    },  
    10, // x
    20, // y
    {{1,2,3,4,5,6,7,8,9,10},80}, // a
    {{1,2,3,4,5,6,7,8,9,10},80}, // b
    {{1,2,3,4,5,6,7,8,9,10},80}  // c
  };

我會考慮以不同的方式設計它,但是我不知道您要解決什么問題。

初始化為全0

XYZ xyz = {};

沒有初始化: http//ideone.com/wE7MCF→未定義行為

初始化: http : //ideone.com/BT81PH→全0

你為什么不上課? 在該類中,您還可以定義一個參數化的構造函數。

還是只想使用結構?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM