static / static const 프로퍼티의 선언과 초기화에 대해 질문드립니다 .

naddolki의 이미지

static / static const 프로퍼티의 선언과 초기화에 대해 ..
궁금해서 질문 올립니다 .

enum Sex {MALE, FEMALE};

class Person
{
public:
static int id;  // 클래스 외부에서만 초기화 가능 --- (1)
static const int age = 20;  // 클래스 내부 혹은, 외부에서 초기화 가능 --- (2)
static const Sex s = FEMALE;  // 클래스 내부 혹은, 외부에서 초기화 가능 --- (3)
static const double weight;  // 클래스 외부에서만 초기화 가능 --- (4)

};

int Person::id = 123;  // (1) 에 대한 외부 초기화
const double Person::weight = 48;  // (4) 에 대한 외부 초기화

void main(void)
{
}

(1) 의 경우는 클래스 외부에서 초기화가 가능하고,
(2), (3) 경우는 클래스 내부나 외부에서 초기화가 가능한데요 .

첫번재 질문 : (2), (3) 의 경우, 왜 클래스 내/외부 모두에서 초기화가 가능한 거죠 ?

두번째 질문 : (4) 의 경우는 (2), (3) 과 마찬가지로, static const 프로퍼티인데 ..
왜 클래스 내부에서 초기화하는 게 허용되지 않는 건가요 ?

이상의 규칙은 .. gcc 에서 그러한 거고요 .
다른 컴파일러에서는 .. gcc 와 다르게 취급합니다 .

컴파일러에 따라, const 프로퍼티를 static const 프로퍼티와 동일한
것으로 간주하는 컴파일러(intel c++)도 있고,
아예 "static const int / static const enum" 프로퍼티의 클래스 내부 초기화를
지원하지 않는 컴파일러(visual c++)도 있더라구요 ;

neogeo의 이미지

2,3 번이 되는 이유는 표준이 그렇게 예외적으로 정해졌기 때문입니다. ( 아마 어디선가 그렇게 써야할 이유가 있었을겁니다. )

If a static data member is of const integral or const enumeration type,
its declaration in the class definition can specify a
constant-initializer which shall be an integral constant expression
(5.19). In that case, the member can appear in integral constant
expressions. The member shall still be defined in a namespace scope if
it is used in the program and the namespace scope definition shall not
contain an initializer.

즉, 2,3 번이 예외다 하고 외우는 수 밖에 없습니다. ( 그렇게 써야할 일이 얼마나 있을지는 조금 의문이지만요. 그냥 외부에서 초기화 해버리면 되죠 뭐.. )

Neogeo - Future is Now.

Neogeo - Future is Now.

naddolki의 이미지

다만 ..

The member shall still be defined in a namespace scope if
it is used in the program and the namespace scope definition shall not
contain an initializer.

이 부분을 준수하지 않아도, gcc 와 intel c++ 에서는 바로 사용할 수 있더군요 .

가령,.. 권고대로라면 ..

class X {
static const int a = 76;
};

const int X::a;

int main() {
cout << X::a << endl;
}

위와 같이 작성해야 동작하는데 ..
아래와 같이만 해줘도 동작하더군요 .

class X {
static const int a = 76;
};

int main() {
cout << X::a << endl;
}

아무튼 이와 관련해서는 굉장히 복잡한 것 같습니다 .
특시, 상속과 관련지었을 때는 더 복잡해지는 것 같고요 ;

그냥 "이런 게 있구나 .." 하고 알아만 두고 ..
넘어가야 하려나 봐요 ^^ ;;

설연희 입니다 ^ ㅡ^ㅋ