강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

씨리얼냠냠님의 프로필 이미지
씨리얼냠냠

작성한 질문수

홍정모의 따라하며 배우는 C++

8.10 정적 멤버 변수

static const 멤버 변수의 주소는 볼 수 없나요?

작성

·

533

0

안녕하세요, 강의 듣던 중 궁금한 점이 있어 질문 드립니다.
#include <iostream>
using namespace std;


class Something
{
    public:
    static const int m_vlaue =1  ;
    int a;

};

// int Something::m_vlaue = 2;

int main()
{
    Something st1;
    Something st2;

    cout << st1.m_vlaue << " " << st2.m_vlaue << endl;
    cout << &st1 << " " << &st2 << endl;
    cout << &st1.m_vlaue << endl;
    cout << &st2.m_vlaue << endl;
    return 0;
}
 
위와 같은 코드를 작성했는데, 마지막에 static const m_value의 주소를 찍어보고 싶은데, 여기서 undefined reference to `Something::m_vlaue' 라는 컴파일 에러가 뜨네요
m_value의 주소는 st1,과 st2가 공유하고 있을 거 같아서 주소를 찍어보고 싶은데, const가 없는 상태에서만 컴파일이 되서 질문드립니다. :)

답변 1

2

안녕하세요,

멤버 변수가static const로 선언되어 있을 경우

컴파일러는 해당 변수를 

리터럴과 다름없는 상수로 간주하여 

해당 변수를 위한 공간을 data 영역에 할당하지를 않습니다.

그래서 당연히 원칙적으로 주소에도 접근할 수 없지요.

 

만일 해당 변수의 주소에 접근하고자 한다면 static const가 아닌 const로 선언하면 됩니다.

#include <iostream>

using namespace std;

class Something
{
    public:
    const int m_vlaue =1;
    int a;
};

// int Something::m_vlaue = 2;

int main()
{
    Something st1;
    Something st2;

    cout << st1.m_vlaue << " " << st2.m_vlaue << endl;
    cout << &st2.m_vlaue << endl;

    cout << &st1.m_vlaue << endl;
    return 0;
}

 

씨리얼냠냠님의 프로필 이미지
씨리얼냠냠

작성한 질문수

질문하기