코딩하렴

C++ DAY4 static method

by 으렴

static method

 

1. class를 통틀어서 오직 하나다

 

2. this pointer가 존재하지 않는다

 

3. instance field를 사용할 수 없다.

 

4. class명 :: 메소드() (많이씀, 압도적으로 static인지 알 수 있음)이렇게 사용도 할 수 있고, 객체.메소드() →객체를 만든 후에 가능

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;
class A
{
public:
    static void disp()
    {
        cout<<"static method"<<endl;
    }
};
 
void main()
{
    A::disp(); // ::(스코프) A클래스에속해있는 메소드얌
}
cs

 

위 코드를 실행하면 static method가 나온다.

 

문제는 위에서

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
class A
{
    int a;
public:
    A(){ a=100; }
    static void disp()
    {
        cout<<"static method"<<a<<endl;
    }
};
 
void main()
{    
    A aa;
    aa.disp();
}
cs

 

static method 뒤의 a는 빨간 색 밑줄이 뜬다.

이는 static에서 this를 참조하지 못했기 때문이다.

static에서 this와 같은 역할을 하기 위해서는 아래와 같이ㅣ 바꿔주면 this의 역할을 수행한다.

 

 

CASE 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;
class A
{
    int a;
public:
    A(){ a=100; }
    static void disp(A *p)
    {
        cout<<"static method"<<p->a<<endl;
    }
};
 
void main()
{
    //A::disp();
    
    A aa;
    aa.disp(&aa);
}
cs

 

CASE 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
class A
{
    int a;
public:
    A(){ a=100; }
    static void disp(A &th)
    {
        cout<<"static method"<<th.a<<endl;
    }
};
 
void main()
{
    A aa;
    aa.disp(aa);
}
cs

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;
class A
{
    static int a;
public:
    A(){ a=100; }
    static void disp() // static field를 관리하기 위해서 만든 
    {
        cout<<"static method"<<a<<endl;
    }
};
int A::a=300;        //static을 쓸 때에는 꼭 외부에서 선언해야 한다.
 
void main()
{
    A::disp();
 
    //A aa;
    //aa.disp(aa);
}
cs

 

c++은 static instance를 선언과 동시에 초기화하는 것이 불가하기 때문에 클래스 내의 멤버를 초기화 하기위해서는

클래스 외부에서 선언(초기화)를 해 주어야 한다.

 

 

 

static은 field내에서 초기화 불가하다 java는 가능하다.

 

초기화를 쓰기위해 콜론초기화기법 (값을 넣겠다)

 

const member :  함수내에서 필드 값 못바꿈.

const는 많이 쓰면 쓸 수록 안정적이다 ( 캡슐화: 많은값을 일일히 확인 할 수고 가 덜어짐 버그가 감소할 수 있다.)

'Programming Language > C and Cpp' 카테고리의 다른 글

C++ DAY5 Is-a관계  (0) 2018.03.14
C++ DAY4 const  (0) 2018.03.08
C++ 복사 생성자 / 소멸자 함수  (0) 2018.03.08
C++ DAY3 class와 생성자 함수  (1) 2018.03.07
C++ 명시적 오버로딩 / 암시적 오버로딩  (0) 2018.03.06

사이트의 정보

코딩하렴

으렴

활동하기