C++ Equivalent to Designated Initializers?

后端 未结 6 1869
萌比男神i
萌比男神i 2020-11-29 05:31

Recently I\'ve been working on some embedded devices, where we have some structs and unions that need to be initialized at compile time so that we can keep certain things in

6条回答
  •  一个人的身影
    2020-11-29 06:23

    #ifdef __cplusplus
    struct Foo
    {
        Foo(int a, int b) : a(a), b(b) {}
        int a;
        int b;
    };
    
    union Bar
    {
        Bar(int a) : a(a) {}
        Bar(float b) : b(b) {}
        int a;
        float b;
    };
    
    static Foo foo(1,2);
    static Bar bar1(1);
    static Bar bar2(1.234f);
    #else 
     /* C99 stuff */
    #endif // __cplusplus
    

    In C++ union can have constructors too. May be this is what you wanted?

提交回复
热议问题