cpp_class_template - 8BitsCoding/RobotMentor GitHub Wiki
ํด๋์ค๋ ํ ํ๋ฆฟ์ ๋ง๋ค ์ ์๋์?
class MyIntArray
{
public:
bool Add(int data);
MyIntArray();
private:
enum { MAX = 3 }; // ์ด๋ฐ์์ผ๋ก ์ด๊ธฐ Array์ ๊ฐ์๋ฅผ ์ ์ธ(์ฅ์ ์ด ์๋๋ฐ ๊ฐ์์ ๋ค์ ๊ฒ.)
int mSize;
int mArray[MAX];
};
// main
#include "MyIntArray.h"
int main() {
MyIntArray scores;
scores.Add(10); // true
scores.Add(20); // true
scores.Add(30); // true
scores.Add(40); // false
}
Add์ intํ๋ง ๊ฐ๋ฅํ๊ฒ ํ ๊ฒ์ธ๊ฐ?
์ฃผ์ํ ์ ์ ํด๋์ค ํ ํ๋ฆฟ์ ๊ฒฝ์ฐ ํค๋ํ์ผ์ ์ ์ธ๋ถ๋ ๋ค์ด๊ฐ์ผํ๋ค๋ ์
๊ทธ๋ ์ง ์์ ์ ์ปดํ์ผ ์๋ฌ ๋ฐ์
// MyArray.h
#pragma once
template<typename T>
class MyArray {
public:
bool Add(T data);
MyArray();
private:
enum { MAX = 3 };
int mSize;
T mArray[MAX];
};
template<typename T>
bool MyArray<T>::Add(T data)
{
// do something
}
template<typename T>
MyArray<T>::MyArray() :
mSize(0)
{
}
// main
MyArray<int> scores; // OK
MyArray scores; // Error
Vector์ ํฌ๊ธฐ๋ฅผ ๋ด๊ฐ ์ง์ ํ๊ณ ์ถ๋ค.(FixedVector)
// FixedVector.h
template<typename T, size_t N>
class FixedVector
{
public:
//
private:
T mArray[N];
};
template<typename T, size_t N>
FixedVector<T, N>::FixedVector() :
mSize(0)
{
}
// others
// main.cpp
FixedVector<int, 16> number;