Proper way to initialize C++ structs

后端 未结 6 536
误落风尘
误落风尘 2020-12-07 08:11

Our code involves a POD (Plain Old Datastructure) struct (it is a basic c++ struct that has other structs and POD variables in it that needs to get initialized in the beginn

6条回答
  •  爱一瞬间的悲伤
    2020-12-07 09:08

    I write some test code:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    struct sc {
        int x;
        string y;
        int* z;
    };
    
    int main(int argc, char** argv)
    {
       int* r = new int[128];
       for(int i = 0; i < 128; i++ ) {
            r[i] = i+32;
       }
       cout << r[100] << endl;
       delete r;
    
       sc* a = new sc;
       sc* aa = new sc[2];
       sc* b = new sc();
       sc* ba = new sc[2]();
    
       cout << "az:" << a->z << endl;
       cout << "bz:" << b->z << endl;
       cout << "a:" << a->x << " y" << a->y << "end" << endl;
       cout << "b:" << b->x << " y" << b->y <<  "end" <x << " y" << aa->y <<  "end" <x << " y" << ba->y <<  "end" <

    g++ compile and run:

    ./a.out 
    132
    az:0x2b0000002a
    bz:0
    a:854191480 yend
    b:0 yend
    aa:854190968 yend
    ba:0 yend
    

提交回复
热议问题