나혼자 공부장

[윤성우] Chap 13. 템플릿 tasks write-up 본문

C++/윤성우

[윤성우] Chap 13. 템플릿 tasks write-up

라부송 2020. 2. 7. 17:53
#include <iostream>
using namespace std;

class Point {
private:
	int xpos, ypos;
public:
	Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
	void SetPos(int x, int y) {
		xpos = x;
		ypos = y;
	}
	void ShowPosition() const {
		cout << '[' << xpos << ", " << ypos << ']' << endl;
	}
};

template <class T>
class SmartPtr {
private:
	T* posptr;
public:
	SmartPtr(T* ptr) : posptr(ptr) {}
	T& operator*() const { return *posptr; }
	T* operator->() const { return posptr; }
	~SmartPtr() { delete posptr; }
};

int main(void) {
	SmartPtr<Point> sptr1(new Point(1, 2));
	SmartPtr<Point> sptr2(new Point(3, 4));
	sptr1->ShowPosition();
	sptr2->ShowPosition();
}

문제 1.

인자로 전달되는 두 변수에 저장된 값을 서로 교환하는 SwapData라는 이름의 함수를 템플릿으로 정의해보자. 그리고 다음 Point 클래스를 대상으로 값의 교환이 이뤄짐을 확인할 수 있도록 main 함수를 구성해보자.

 

class Point {
private:
int xpos, ypos;
public:
Point(int x=0, int y=0) : xpos(x), ypos(y) {}
void ShowPosition() const {
cout << '[' << xpos << ", " << ypos << ']' << endl;
}
};

#include <iostream>
using namespace std;

template <class T>
void SwapData(T &x, T &y) {
	T temp = x;
	x = y;
	y = temp;
}

class Point {
private:
	int xpos, ypos;
public:
	Point(int x=0, int y=0) : xpos(x), ypos(y) {}
	void ShowPosition() const {
		cout << '[' << xpos << ", " << ypos << ']' << endl;
	}
};

int main(void) {
	Point pos1(1, 2);
	Point pos2(10, 20);
	pos1.ShowPosition();

	SwapData(pos1, pos2);
	pos1.ShowPosition();
	pos2.ShowPosition();
	return 0;
}

 

 

문제 2.

다음은 i nt형 배열에 저장된 값을 모두 더해서 그 결과를 반환하는 기능의 함수이다.

 

int SumArray(int arr[], int len) {
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}

#include <iostream>
using namespace std;

template <class T>
int SumArray(T arr[], int len) {
	int sum = 0;
	for (int i = 0; i < len; i++) {
		sum += arr[i];
	}
	return sum;
}

int main(void) {
	int intarr[] = { 1,2,3,4,5,6,7,8,9,10 };
	char chararr[] = { 'A','B','C','D','E','F','G','H','I','J' };

	cout << SumArray(intarr, sizeof(intarr) / sizeof(int)) << endl;
	cout << SumArray(chararr, sizeof(chararr) / sizeof(char)) << endl;

	return 0;
}

 

문제 3.

스마트 포인터를 템플릿을 통해 구현

#include <iostream>
using namespace std;

class Point {
private:
	int xpos, ypos;
public:
	Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
	void SetPos(int x, int y) {
		xpos = x;
		ypos = y;
	}
	void ShowPosition() const {
		cout << '[' << xpos << ", " << ypos << ']' << endl;
	}
};

template <class T>
class SmartPtr {
private:
	T* posptr;
public:
	SmartPtr(T* ptr) : posptr(ptr) {}
	T& operator*() const { return *posptr; }
	T* operator->() const { return posptr; }
	~SmartPtr() { delete posptr; }
};

int main(void) {
	SmartPtr<Point> sptr1(new Point(1, 2));
	SmartPtr<Point> sptr2(new Point(3, 4));
	sptr1->ShowPosition();
	sptr2->ShowPosition();
}

'C++ > 윤성우' 카테고리의 다른 글

[윤성우] Chap 14. 템플릿(template) 2  (0) 2020.02.07
[윤성우] Chap13. 템플릿(template)  (0) 2020.02.07
Comments