How to use a struct inside another struct?

前端 未结 7 1328
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 21:05

I want to use a nested structure but i dont know how to enter data in it, for example:

struct A {
    int data;
    struct B;
};
struct B {
    int number;
};


        
相关标签:
7条回答
  • 2021-02-05 21:15
    struct B {  // <-- declare before
      int number;
    };
    struct A {
     int data;
     B b; // <--- declare data member of `B`
     };
    

    Now you can use it as,

    stage.b.number;
    
    0 讨论(0)
  • 2021-02-05 21:18

    The struct B within A must have a name of some sort so you can reference it:

    struct B {
        int number;
    };
    struct A {
        int data;
        struct B myB;
    };
    :
    struct A myA;
    myA.myB.number = 42;
    
    0 讨论(0)
  • 2021-02-05 21:20

    Each member variable of a struct generally has a name and a type. In your code, the first member of A has type int and name data. The second member only has a type. You need to give it a name. Let's say b:

    struct A {
      int data;
      B b;
    };
    

    To do that, the compiler needs to already know what B is, so declare that struct before you declare A.

    To access a nested member, refer to each member along the path by name, separated by .:

    A stage;
    stage.b.number = 5;
    
    0 讨论(0)
  • 2021-02-05 21:27
    struct A {
        struct B {
           int number;
        };
        B b;
        int data;
    };
    int main() {
        A a;
        a.b.number;
        a.data;
    }
    
    0 讨论(0)
  • 2021-02-05 21:29
    struct A 
    {
      int data;
      struct B
      {
        int number;
      }b;
    };
    
    int main()
    {
      A stage = { 42, {100} };
      assert(stage.data == 42);
      assert(stage.b.number == 100);   
    }
    
    0 讨论(0)
  • 2021-02-05 21:39
    struct TestStruct {
        short Var1;
        float Var2;
        char Var3;
    
        struct TestStruct2 {
            char myType;
            CString myTitle;
            TestStruct2(char b1,CString b2):myType(b1), myTitle(b2){}
        };
    
        std::vector<TestStruct2> testStruct2;
    
        TestStruct(short a1,float a2,char a3): Var1(a1), Var2(a2), Var3(a3) {
            testStruct2.push_back(TestStruct2(0,"Test Title"));
            testStruct2.push_back(TestStruct2(4,"Test2 Title"));
        }       
    };
    std::vector<TestStruct> testStruct;
    
    //push smthng to vec later and call 
    testStruct.push_back(TestStruct(10,55.5,100));
    TRACE("myTest:%s\n",testStruct[0].testStruct2[1].myTitle);
    
    0 讨论(0)
提交回复
热议问题