简体   繁体   中英

How to initialize specific members of a C-struct in C++

I am writing a C++ struct which contains a C-struct. The C-struct is included by other.c files, so I cannot change it to C++.

I want to make sure that every member is of the c++ struct is initialized. So I have used in-class initialization and constructor initilizer where needed:

struct CppStruct 
{
    CStruct pod {};    // initialize all members to 0
    int i = 0;
    double d = 0.0;

    CppStruct()  
    { }

    CppStruct(int another_val) 
        : i(another_val) 
    { }
};

This initializes all the members of the CStruct to zeroes. Zeroes are fine for most members of the c-struct, but unfortunately, it also contains a C-enum whithout a zero-value:

// C-header
enum Color {  // no '0' entries here!
  red = 1,
  yellow = 2;
};

struct CStruct { // this struct can potentially contain a lot of members
    int i;
    int j;
    Color col;
    int m;
    int n;
};

The only way I have found to write the constructor is this, but this theoretically sets the pod.col member twice:

    CppStruct()  
    { pod.col = Color::red; }

    CppStruct(int another_val) 
        : i(another_val) 
    { pod.col = Color::red; }

Is there anyway I can override the initialization of selected members of the pod , without having to specify all its members?

eg I tried this but it does not compile:

    CppStruct()  : pod.col(Color::red) {}  

The following is legal, but I want to avoid it, in case the CStruct is changed/shuffled by another colleague:

    CppStruct()  : pod{0,0,Color::red,0,0} {}

The best way I think is to just overwrite the col value inside the constructor, don't worry about multiple initializations, as it's just an enum, not a massive object, so the performance difference is somewhat nothing (unless you are really desperate for performance).

A quick and dirty way to achieve initialization the way you wanted is to create a static function that would return a default CStruct like that:

struct CppStruct 
{
    CStruct pod {};    // initialize all members to 0
    int i = 0;
    double d = 0.0;

    CppStruct()
        : pod(_get_default_pod())
    { }

    CppStruct(int another_val) 
        : i(another_val), pod(_get_default_pod())
    { }
        
private:
    static inline CStruct _get_default_pod() {
        CStruct pod {};
        pod.col = Color::red;
        return pod;
    };
};

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