LANGUAGE/C++
[C++] STATIC
진심스테이크
2018. 3. 8. 10:15
static method
생성시기 : 맨 처음
특징
1. class를 통 틀어서 오직 하나다
2. this pointer가 존재하지 않는다
3. instance field를 사용할 수 없다
기본 형태
클래스명::메소드( );
객체.메소드( ); //객체를 만든 후
# :: - 범위 지정 연산자 (스코프) : 클래스 이름과 static 멤버 사이에서 static 멤버를 접근하기 위해 사용
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
class A {
public :
static void disp() {
cout << "static method" << endl;
}
};
void main() {
A::disp(); //static method 호출
//A클래스 함수의 disp()
}
static field
외부에서 꼭 선언을 해야 한다
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
class A {
static int a; //선언이 아님 -> 링크를 걸어주는 개념
public :
A() {
a = 100; //초기화 되는게 아님
}
static void disp() {
cout << "static method" << endl;
cout << a << endl;
}
};
int A::a = 300; //멤버
void main() {
A::disp();
}
#전역 변수 : main함수 밖에 쓰는 함수