c++ 클래스에서 const 와 static 변수 선언에 관한내용 짧습니다

gyxor의 이미지

#include<iostream>
using namespace std;

class tri 
{
 private:
    static int x;              //<1>
    const  int y=10;        //<2> 
    static const int z=50; //<3>        
    
    public:
};
int tri:: x=555;
void main()
{
}

위 내용에서 1번의 경우엔 static 변수이므로 외부에서 따로

선언을 해주고요

나머지 const 변수가 들어가 있는 선언의 경우엔 클래스 안에서

선언이 가능하다고 책에 나와있는데요

왜 에러가 나는지 모르겠습니다.

또한 1>번의 경우에도 내부 선언이 가능할것 같은데요

이내용에 관한 설명 부탁드립니다.

맹고이의 이미지

Quote:
When you create an ordinary(non-static)const inside a class, you cannot
give it an initial value. This is initialization must occur in the constructor,
of course, but in a special place in the contsructor.
Because a const must be initialized at the point it is created,
inside the main body if the constructor the const must already be initialized.
Otherwise you're left with the choice of waiting until some point later in the
constructor body, which means the const would be un-initialized for a while.
also, there would be nothing to keep you from changing the value of the const
at various places in the constructor body.

Thinking in C++
P.353

헥헥.. 번역능력이 딸려서 그냥 그대로 올려봤습니다..

#include<iostream>
using namespace std;

class tri {
private:
    static int x;                    //<1>
    const  int y;                  //<2>
    static const int z = 50;    //<3>

public:
    tri(int yy);
};
tri::tri(int yy) : y(yy) {} 
int tri:: x = 555;
int main() {}

아시겠지만.. 이런식으로 초기화 해야겠네용

p.s. 흠냐 후다닥 적었더니 오탈자가 많아서 계속 고칩니다;;

clhitter의 이미지

위에 분이 2번 경우는 잘 설명해주신 것 같구요
1 번의 경우는 ODR (one definition rule)을 어기기 때 안되는 겁니다.
ODR라는 것은 전체 프로그램에서 변수, 함수 등은 한번만 정의(!) 되어야 한다는 규칙인데
header에
static int x = 555;
이렇게 정의가 되어 있다면 이 헤더를 #include 한 모든 translation unit에서 x 변수가 정의되므로 ODR을 어기게 되는 것이죠
3번 경우는 이것의 예외입니다. integral const의 경우는 메모리가 할당되는 변수로 처리하지 않고 마치 #define 처럼 컴파일 타임에서 상수로 치환을 해주면 ODR을 어디기 않을 수 있거든요 (이런걸 in-class static const integral initializer라고 합니다.)
원래는 3번이 맞는 문법인데 에러가 나는 것은 사용하시는 컴파일러가 VC6 처럼 in-class static const integral initializer를 지원하지 않기 때문인거 같네요 )