반응형
안녕하세요. 훈츠입니다. 금일은 Template 키워드를 이용하여 클래스에 적용 하는 방법에 대해 포스팅 합니다.
템플리트 클래스(template class)
- 클래스 안에서 사용하려는 형을 템플리트로 지정 합니다.
- 템플리트를 사용하는 멤버 함수의 구현을 외부에서 할때에는 클래스에서 정의한 템플리트를 모든 함수의 구현 부분에 지정해 줘야합니다.
형식 ( template 클래스 선언 )
- template 뒤에 클래스 선언
- template<class T> class A { ….;
예제1 코드 (T 가하나인 경우)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
template<class T> class A
{
private: T m_Var;
public:
void Print();
void Set(T Var);
T Get() { return m_Var; }
};
template<class T> void A<T>::Set(T var) {
m_Var = var;
}
template<class T>void A<T>::Print() {
cout<<"m_Var 출력값 " << m_Var << endl;
}
int main()
{
A<int> test1;
A<char> test2;
A<char*> test3;
test1.Set(200);
test2.Set('C');
char str[] = "C++ Template example";
char* ptr = &str[0];
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
template <class T> class A 선언 방식을 잘기억하고 있다가 입력들어오는 타입만 달라지는 경우 사용하면 편리 합니다.
예제2 코드 ( 두가지 T, U,V TYPE 받는 예시 )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
template<class T, class U, class V> class A
{
private:
T m_VarT;
U m_VarU;
V m_VarV;
public:
void Print();
void Set(T Var);
void Set(U Var);
void Set(V Var);
};
template<class T,class U,class V> void A<T,U,V>::Set(T var) {
m_VarT = var;
}
template<class T, class U, class V> void A<T, U, V>::Set(U var) {
m_VarU = var;
}
template<class T, class U, class V> void A<T, U, V>::Set(V var) {
m_VarV = var;
}
template<class T,class U,class V>void A<T,U,V>::Print() {
cout<<"m_Var 출력값 " << m_VarT<<'\t'<< m_VarU<<'\t'<< m_VarV << endl;
}
int main()
{
A<int,char,char*> test;
test.Set(200);
test.Set('C');
char str[] = "C++ Template example";
char* ptr = &str[0];
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |