개발 소발/개발 C++(기초)
c++ static 정적멤버변수,정적멤버함수
우기!
2019. 8. 8. 15:27
정적멤버변수 (static)
정적변수는 한번선언되면 초기화하지않고 계속 증가한다.
정적멤버변수도 마찬가지로 한 메모리 주소를 보고 있기에
인스턴스를 몇번이고 생성해도 같은 변수주소를 보고 있다.
static만 선언하면 변수를 클래스 밖에서 초기화해주어야하고
static const로 선언하면 클래스안에서 초기화가 가능하다.
#include <iostream>
using namespace std;
int generateID() {
static int s_id = 0;
cout << &s_id << endl;
return ++s_id;
}
class Something
{
public:
static int s_value;
};
int Something::s_value = 1;
int main()
{
//계속 늘어나는걸 볼 수 있다.
cout << generateID() << endl;
cout << generateID() << endl;
cout << generateID() << endl;
Something st1;
Something st2;
st1.s_value = 2;
cout << &st1.s_value << " " << st1.s_value << endl;
cout << &st2.s_value << " " << st2.s_value << endl;
return 0;
}
정적멤버함수
정적멤버함수와 정적멤버변수와 비슷한듯 다르다.
정적멤버변수,함수는 인스턴스로 정의되기전 클래스 접근 또는
모든 인스턴스에서 접근이가능하다. (메모리공유)
정적멤버함수는 this를 사용하지 못한다.
정적멤버함수는 정적멤버변수만 리턴할 수 있다.
#include <iostream>
using namespace std;
class Something
{
private:
static int m_value;
int p_value = 1024;
public:
Something() {
}
static int getValue() {
return m_value+1;
}
int getPValue() {
return this -> p_value + this ->m_value;
}
};
int Something::m_value = 1024;
int main()
{
cout << Something::getValue << endl;
cout << Something::getValue() << endl;
Something st;
cout << st.getValue() << endl;
//멤버함수
int(Something::*ptr)() = &Something::getPValue;
//정적멤버함수
int (*ptr2)() = Something::getValue;
cout << "=============" << endl;
cout << (st.*ptr)() << endl;
cout << (*ptr2)() << endl;
return 0;
}