Review:template ํ•จ์ˆ˜

Icarus<Wing>ยท2022๋…„ 10์›” 12์ผ
0

๐Ÿค” template ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ class์˜ ๋ฐ์ดํ„ฐํƒ€์ž…์„ ์ผ๋ฐ˜ํ™”ํ•ด๋ณด์ž.

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์˜ ๊ฐ’๋“ค์„ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋กœ ์ดˆ๊ธฐํ™”์‹œํ‚จ๋‹ค.
  • class ์™ธ๋ถ€์— ์ •์˜ํ•  ๋•Œ๋Š” ์‚ฌ์šฉ๋ฒ”์œ„ ๊ฒฐ์ • ์—ฐ์‚ฐ์ž '::'๋ฅผ ๋„ค์ž„์ŠคํŽ˜์ด์Šค ์˜†์— ์‚ฌ์šฉํ•˜์—ฌ class์— ์ ‘๊ทผํ•˜๋„๋ก ํ•œ๋‹ค.

class๋ฅผ ํ…œํ”Œ๋ฆฟํ™”

#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์œ„์— template <class T>(๋˜๋Š” <typename T>)๋กœ ์„ ์–ธํ•œ๋‹ค.
    • class๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๋ฐ์ดํ„ฐํ˜•๋„ ํ…œํ”Œ๋ฆฟํ™”๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค <-๊ทธ๋ž˜์„œ ๋ฐ์ดํ„ฐํ˜•์ด ๋‹ค๋ฅผ๋•Œ๋งˆ๋‹ค class๋ฅผ ๋งŒ๋“ค ํ•„์š”๊ฐ€ x
  • class ์™ธ๋ถ€์— ์ƒ์„ฑ์ž ๋˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•  ๋•Œ๋งˆ๋‹ค template <class T>๋ฅผ ์„ ์–ธํ•ด์ค˜์•ผํ•˜๋ฉฐ, ๋„ค์ž„์ŠคํŽ˜์ด์Šค์˜†์— <T>๋ฅผ ์จ์„œ ํ…œํ”Œ๋ฆฟํ™” ํ•ด์ค˜์•ผํ•œ๋‹ค.
  • ๋ฉ”์ธํ•จ์ˆ˜์—์„œ ์ƒ์„ฑ์ž๋ฅผ ์„ ์–ธํ• ๋•Œ๋Š” <int>์™€ ๊ฐ™์ด ํด๋ž˜์Šค์˜†์— ๋ฐ์ดํ„ฐํƒ€์ž…์„ ๋ช…์‹œํ•ด์ค˜์•ผํ•œ๋‹ค.
profile
๋ชจ๋“  ์ฝ”๋“œ์—๋Š” ์ด์œ ๊ฐ€ ์žˆ๊ธฐ์— ์›์ธ์„ ํŒŒ์•…ํ•  ๋•Œ๊นŒ์ง€ ์ง‘์š”ํ•˜๊ฒŒ ํƒ๊ตฌํ•˜๋Š” ๊ฒƒ์„ ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€