private static member 초기화하는 법
조회수 6496회
private static member
는 어떻게 초기화하나요?
제가 한 방법은 에러가 뜨네요 ㅜㅜ
에러메세지
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
소스코드
class foo
{
private:
static int i;
};
int foo::i = 0;
1 답변
-
헤더 파일에서 i를 초기화해서 그렇습니다.
static
변수를 쓸 때 클래스 선언은 헤더 파일에 있어도 되지만static
변수의 초기화는 소스파일에서 해줘야 합니다.예를 들어 foo.h)
class foo { private: static int i; };
foo.c/foo.cpp)
int foo::i = 0;
처럼요.
이렇게 해야 하는 이유는 여러 개의 소스파일에서 헤더를 동시에 include하면 여러 개의 소스파일 모두 초기화하는 코드를 갖게 되므로 링크 단계에서 에러를 내주는 것이지요
단,
static const
는 헤더 파일에서 다음과 같이 쓸 수 있습니다. 다만integra
l/enum
형에서만 가능하니 주의하세요foo.h)
class foo { private: static int const i = 42; };
댓글 입력