본문 바로가기
열혈강의c++

[ 열혈C++ ] Chapter 13 연습문제

by 어린왕자1234 2022. 7. 21.

문제13-1 [함수 템플릿의 정의]

문제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;
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;
	}
};

template <typename T>
void Swap(T& num1, T& num2)
{
	T temp = num1;
	num1 = num2;
	num2 = temp;
}
int main(void)
{
	Point pos1(3, 4);
	Point pos2(10, 20);
	pos1.ShowPosition();
	pos2.ShowPosition();
	cout << "Swap 함수 실행결과" << endl;
	Swap(pos1, pos2);
	pos1.ShowPosition();
	pos2.ShowPosition();
	return 0;
}

 

문제2

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

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<typename T>
T SumArray(T arr[], int len)
{
	T sum = 0;
	for (int i = 0; i < len; i++)
		sum += arr[i];
	return sum;
}

int main(void)
{
	int arr[3] = { 1,2,3 };
	cout << SumArray<int>(arr, sizeof(arr)/sizeof(int))<<endl;
	double arr1[3] = { 1.1,2.2,3.3 };
	cout << SumArray<double>(arr1, sizeof(arr1) / sizeof(double))<<endl;
	return 0;
}

 

문제13-2 [클래스 템플릿의 정의]

만약에 Chapter 11을 공부하면서 스마트 포인터도 공부를 했다면, 이문제를 반드시 해결하고 넘어가기 바란다.
! 그럼 문제를 제시하겠다. 우리는 앞서 Chapter 11에서 다음의 형태로 스마트 포인터를 정의하였다.

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

이 스마트 포인터를 템플릿으로 정의하여, 어떠한 클래스의 객체도 참조할 수 있는 포인터가 되게하자.
그리고는 아래의 Point 클래스와 main 함수를 기반으로 예제를 완성해보자.
참고로 스마트 포인터는 이렇듯 템플릿의 형태로 정의가 된다.

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;
        }
};
 
int main(void)
{
        SmartPtr<Point> sptr1(new Point(1, 2));
        SmartPtr<Point> sptr2(new Point(3, 4));
        sptr1->ShowPosition();
        sptr2->ShowPosition();
        sptr1->SetPos(10, 20);
        sptr2->SetPos(30, 40);
        sptr1->ShowPosition();
        sptr2->ShowPosition();
        return 0;
}

 

main.cpp
0.00MB
Point.h
0.00MB
SmartPtr.h
0.00MB