在类构造函数中初始化结构的正确方法

tzi*_*ppy 28 c++ struct c++11

所以我想从ac头文件中添加一个结构作为类成员到c ++类.但是我收到了cpp文件的编译错误:bar was not declared inn this scope.这就是我所拥有的:

//    myClass.hpp
#include fileWithStruct.h

class myClass
{
    public:
        struct foo bar;
};


//myClass.cpp

#include "myClass.hpp"

//Initialize structure in Constrcutor
myClass::myClass(  )
{
    bar = {1, 0, "someString", 0x4};
}
Run Code Online (Sandbox Code Playgroud)

leg*_*s2k 33

C++ 03风格

#include "fileWithStruct.h"
/* say the contents were
struct foo
{
   int foo1;
   float foo2;
};
*/

class myClass
{
    public:
        int val;
        foo bar;
        // since foo is a POD-struct (a.k.a C struct), no constructor would be present
        // however bar() will zero-initialize everything in the struct
        myClass() : val(), bar()
        {
        }
};
Run Code Online (Sandbox Code Playgroud)

后面的括号bar事项.请参考值和零初始化以了解其工作原理.需要注意的是,通过添加构造函数myClass,我们使其成为非POD类型.要解决这个问题,可以保留myClass为聚合并写入:

class myClass
{
    public:
        int val;
        foo bar;
};

int main()
{
   myClass zeroed_obj = { };
   myClass inited_obj = { 2, {0, 1.0f} };
   myClass partially_inited_obj = { 2 };    // equivalent to {2, {}}; which would zero all of myClass::bar
   myClass garbage_obj;    // warning: when left uninitialized, every member without a constructor will end up with garbage value
}
Run Code Online (Sandbox Code Playgroud)

C++ 11风格

class myClass
{
public:
   // default member initializations
   int val = { };         // zero-initialization
   foo bar = { 0, 0.0f }; // aggregate-initializing foo here, just giving { } will zero all of myClass::bar

   // should you want to receive an element from the constructor, this can be done too
   // aggregate initializing a struct in constructor initialization list is allowed from C++11 onwards
   // in C++03, we would've resorted to just setting the member of bar inside the constructor body
   myClass(int _foo1) : bar{_foo1, 0.f}, val{}
   {
   }

   // since we've a non-default constructor, we've to re-introduce the default constructor
   // if we need the above in-class initialization to work
   myClass() = default;
};
Run Code Online (Sandbox Code Playgroud)

这里我们使用C++ 11的统一初始化语法.但是,通过这样myClass做成为非POD类型; 成员初始化类似于向类中添加构造函数,从而呈现myClass一个非平凡但标准的布局类.根据C++ 11,对于要成为POD的类,它应该是平凡的和标准的布局.相反做

#include "fileWithStruct.h"
#include <type_traits>
#include <iostream>

class myClass
{
public:
   int val;
   foo bar;
};

int main()
{
    myClass obj { }; // initializes val, bar.foo1 and bar.foo2 to 0
    myClass m { 0, {1, 2.0f} }; // initilizes each member separately
    std::cout << std::is_pod<myClass>::value << std::endl; // will return 1
}
Run Code Online (Sandbox Code Playgroud)

将保留myClass为POD.

请参阅此优秀帖子以了解有关聚合和POD的更多信息.

  • 你不需要在C++ 03或C++ 11中使用`struct foo bar;`,只需`foo bar;`就可以了.此外,在C++ 11中,您可以在声明点初始化`bar`. (3认同)

Arn*_*rtz 9

你在做什么是分配,而不是初始化.初始化发生在构造函数的初始化列表中,构造函数体之前,或者在成员变量声明之后的初始化程序中的C++ 11中:

myClass.hpp,一般情况:

/** 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
};
Run Code Online (Sandbox Code Playgroud)

C++ 11:

myClass.cpp

#include "myClass.hpp"

//Initialize structure in Constrcutor
myClass::myClass(  )
  : bar{1, 0, "someString", 0x4}
{}
Run Code Online (Sandbox Code Playgroud)

Antoher选项是在成员变量声明中提供foo的初始值和一个大括号或等于初始化器:

myClass.hpp

extern "C" { 
  #include fileWithStruct.h
}

class myClass
{
public:
  foo bar{1, 0, "someString", 0x4};
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您无需定义构造函数,因为它是由编译器隐式生成的(如果需要),正确初始化bar.

C++ 03:

这里初始化列表中的聚合初始化不可用,因此您必须使用变通方法,例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

要么:

#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
{ }
Run Code Online (Sandbox Code Playgroud)


Mat*_*get 7

应该以这种方式进行初始化(C++ 11):

myClass::myClass(  )
: bar{1, 0, "someString", 0x4}
{

}
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记在类定义中声明构造函数.