๐ค template ํจ์๋ฅผ ์ฌ์ฉํ์ฌ class์ ๋ฐ์ดํฐํ์ ์ ์ผ๋ฐํํด๋ณด์.
#include <iostream>
using namespace std;
class Arithmathic
{
private:
int a;
int b;
public:
Arithmathic(int, int);
int add();
int sub();
~Arithmathic();
};
Arithmathic::Arithmathic(int a, int b)
{
this->a = a;
this->b = b;
//this indicates oneself(class)
}
int Arithmathic::add()
{
int c;
c = a + b;
return c;
}
int Arithmathic::sub()
{
int c;
c = a - b;
return c;
}
Arithmathic::~Arithmathic()
{
}
int main()
{
Arithmathic ar(3, 10);
cout << ar.add() << endl;
cout << ar.sub() << endl;
return 0;
}
this->a = a์ this->b = b๋ this๊ฐ ํฌ์ธํฐ ํ์์ด๊ณ ๊ฐ์ฒด ์๊ธฐ์์ ์ ๊ฐ๋ฆฌํค๊ธฐ ๋๋ฌธ์, parameter์ ๊ฐ๋ค์ ๋ฉค๋ฒ๋ณ์๋ก ์ด๊ธฐํ์ํจ๋ค.#include <iostream>
using namespace std;
template <class T>
class Arithmathic
{
private:
T a;
T b;
public:
Arithmathic(T, T);
T add();
T sub();
~Arithmathic();
};
template <class T>
Arithmathic<T>::Arithmathic(T a, T b)
{
this->a = a;
this->b = b;
//this indicates oneself(class)
}
template <class T>
T Arithmathic<T>::add()
{
T c;
c = a + b;
return c;
}
template <class T>
T Arithmathic<T>::sub()
{
T c;
c = a - b;
return c;
}
template <class T>
Arithmathic<T>::~Arithmathic()
{
}
int main()
{
Arithmathic<int> ar(3, 10);
cout << ar.add() << endl;
cout << ar.sub() << endl;
Arithmathic<float> ar2(3.5, 2.9);
cout << ar2.add() << endl;
cout << ar2.sub() << endl;
return 0;
}
template <class T>(๋๋ <typename T>)๋ก ์ ์ธํ๋ค.template <class T>๋ฅผ ์ ์ธํด์ค์ผํ๋ฉฐ, ๋ค์์คํ์ด์ค์์ <T>๋ฅผ ์จ์ ํ
ํ๋ฆฟํ ํด์ค์ผํ๋ค.<int>์ ๊ฐ์ด ํด๋์ค์์ ๋ฐ์ดํฐํ์
์ ๋ช
์ํด์ค์ผํ๋ค.