당신이하는 일은 할당이 아니라 초기화입니다.
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 이니셜 라이저에서의 생성자의 초기화 목록에서 일어나는
C++ 11 :
MyClass.cpp를
#include "myClass.hpp"
//Initialize structure in Constrcutor
myClass::myClass()
: bar{1, 0, "someString", 0x4}
{}
myClass.hpp
extern "C" {
#include fileWithStruct.h
}
class myClass
{
public:
foo bar{1, 0, "someString", 0x4};
};
이 경우, 당신이 필요가 : 10,403,210 Antoher 옵션은 멤버 변수 선언에서 중괄호 또는 동등한-초기화와 foo는의 초기 값을 제공하는 것입니다 컴파일러에 의해 암시 적으로 생성되므로 (필요한 경우) 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
{ }
'struct foo bar;를 놓기 위해 eed했다. C++ 03이나 C++ 11에서는'foo bar;'만이 그렇게 할 것이다. 또한 C++ 11에서는 선언 시점에서'bar'를 초기화 할 수 있습니다. – juanchopanza
동의하고 답변에서 해결했습니다. 그것은 오래된 C 스타일의 struct 객체 선언 구문입니다. – legends2k
OP는 C 헤더 안에'foo'를 명시 적으로 언급하기 때문에 생성자를 추가하는 것은 옵션이 아닙니다. (그리고 C 헤더에'#ifdef __cplusplus '를 넣어서 고치지 마십시오.) –