你在那里做什么是分配,而不是初始化。初始化发生在构造函数的初始化列表,构造体之前,或在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
};
C++ 11:
myClass.cpp
#include "myClass.hpp"
//Initialize structure in Constrcutor
myClass::myClass()
: bar{1, 0, "someString", 0x4}
{}
Antoher选择是提供foo的初始值与在成员变量声明撑 - 或等于初始值设定:
myClass.hpp
extern "C" {
#include fileWithStruct.h
}
class myClass
{
public:
foo bar{1, 0, "someString", 0x4};
};
在这种情况下,需要不定义构造函数,因为它由编译器隐式生成(如果需要),正确初始化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;
}
或者:
#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
{ }
你没有n在C++ 03或C++ 11中,只需'foo bar;'就可以了。另外,在C++ 11中,你可以在声明处初始化'bar'。 – juanchopanza
同意,修复它的答案。这是旧的C风格结构对象声明语法。 – legends2k
OP明确提到'foo'在C头文件中,因此向它添加一个构造函数不是一个选项。 (请不要通过将'#ifdef __cplusplus'放入C头来解决这个问题) –