简体   繁体   中英

creating empty constructor for struct with anonymous union

Trying to create empty constructor for a struct that has union as a member variable. Union also has a struct and an additional variable as member variables.

Took few approaches, but non were successful. How can I create an empty constructor for nested anonymous structures? How can I call the member variables afterwards?

typedef struct test_struct
{
   int a;
   union {
      int b;
      struct {
         int c;  
      };  
    };
 } test_struct; 

Below won't compile

 test_struct() : a(10), b(20), c(30) {
 }   

Below sets both b and c as 30

test_struct() : a(10), b(20) {
   c = 30;
 }  

Here is the print function

int main(void)
{  
   test_struct *ts = new test_struct();
   printf("%i\n%i\n%i\n", ts->a, ts->b, ts->c);
   return 0;
}

I trying to create an empty constructor that will print 10 20 30 with my printf().

EDIT: I received comments on how I cannot initialize union in this way. However, the header file I received (which I cannot change at all) has structs defined in such nested structure. I do not know how the initialization goes in the back, but my code has to print out values for all the member variables. (a, b, and c for the below example code). Any approaches/reading I can do to achieve this?

Apart from the erroneous way you use union, let's stick to the question about your nested struct. The answer is simple: you can't specify constructors for nested structs. So, even if you fix the code and use correctly your nested struct, you won't be able to declare a constructor or destructor for that anonymous class/struct because the constructor and destructor names need to match the class name. In the example you posted, the anonymous class is local. It means that it has no linkage so mangled name is not even created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM