Correct way of initializing a struct in a class constructor

前端 未结 5 606
灰色年华
灰色年华 2020-12-08 02:44

So I want to add a struct from a c header file as a class member to a c++ class. But I get a compiler error for the cpp file: bar was not declared inn thi

5条回答
  •  隐瞒了意图╮
    2020-12-08 03:00

    What you are doing there is assignment, not initialization. Initialization happens in the initialization list of a constructor, before the constructor body, or in C++11 in an initializer right after the member variable declaration:

    myClass.hpp, general case:

    /** you might want to do this if you are linking 
     * against the C lib or object file of that header:
     */
    extern "C" { 
      #include fileWithStruct.h
    }
    
    class myClass
    {
    public:
      foo bar; //no need for "struct" in C++ here
    };
    

    C++11:

    myClass.cpp

    #include "myClass.hpp"
    
    //Initialize structure in Constrcutor
    myClass::myClass(  )
      : bar{1, 0, "someString", 0x4}
    {}
    

    Antoher option is to provide the initial value of foo with an brace-or-equal-initializer at the member variable declaration:

    myClass.hpp

    extern "C" { 
      #include fileWithStruct.h
    }
    
    class myClass
    {
    public:
      foo bar{1, 0, "someString", 0x4};
    };
    

    In this case, you need not define a constructor, since it's generated implicitly by the compiler (if needed), correctly initializing bar.

    C++03:

    Here aggregate initialization in init lists is not available, so you have to use workarounds, e.g.:

    myClass.cpp

    #include "myClass.hpp"
    
    //Initialize structure in Constrcutor
    myClass::myClass(  )
      : bar() //initialization with 0
    {
      const static foo barInit = {1, 0, "someString", 0x4}; //assignment
      bar = barInit;
    }
    

    Or:

    #include "myClass.hpp"
    namespace {
      foo const& initFoo() {
        const static foo f = {1, 0, "someString", 0x4};
        return f;
      }
    }
    
    //Initialize structure in Constrcutor
    myClass::myClass(  )
      : bar(initFoo()) //initialization
    { }
    

提交回复
热议问题