C++/기초를 탄탄히 세워주는 C++ 프로그래밍 입문(황준하 저)

기초를 탄탄히 세워주는 C++ 프로그래밍 입문 5장 연습문제

꾸준함. 2017. 6. 29. 11:00

[5.1]

/*

예제 5.4의 프로그램에서 3 2열의 CPoint 객체 배열을 생성하되,

배열 선언시에는 별도의 초기화를 하지 않고 단지 선언만 한 후,

사용자로부터 각 원소의  x, y 값을 차례로 입력받도록한다.

그리고 제대로 입력이 되었는지 출력을 통해 확인해보도록 한다

*/

#include <iostream>

using namespace std;

 

class CPoint

{

private:

        int x, y;

public:

        /*

        CPoint(int a, int b) :x(a), y(b)

        {

        }

        */

        void SetXY(int a, int b)

        {

               x = a;

               y = b;

        }

        void Print()

        {

               cout << "(" << x << ", " << y << ")";

        }

};

 

int main(void)

{

        CPoint pt[3][2];

        int x, y;

 

        for (int i = 0; i < 3; i++)

        {

               for (int j = 0; j < 2; j++)

               {

                       cout << "x y값 입력: ";

                       cin >> x >> y;

                       pt[i][j].SetXY(x, y);

               }

        }

        for (int i = 0; i < 3; i++)

        {

               for (int j = 0; j < 2; j++)

               {

                       pt[i][j].Print();

                       cout << "\t";

               }

               cout << endl;

        }

        return 0;

}

 


[5.2]

/*

다음과 같은 main 함수가 실행 결과와 같이 수행될 수 있도록 CPoint 클래스와

GetSumX, GetSumY 함수를 작성해본다

*/

#include <iostream>

using namespace std;

 

class CPoint

{

private:

        int x;

        int y;

public:

        CPoint() :x(0), y(0)

        {

        }

        CPoint(int a, int b) :x(a), y(b)

        {

        }

        void SetXY(int a, int b)

        {

               x = a;

               y = b;

        }

        int GetSumX(CPoint *arr, int num)

        {

               int sum = 0;

               for (int i = 0; i < num; i++)

                       sum += arr[i].x;

               return sum;

        }

        int GetSumY(CPoint *arr, int num)

        {

               int sum = 0;

               for (int i = 0; i < num; i++)

                       sum += arr[i].y;

               return sum;

        }

        void Print()

        {

               cout << "(" << x << ", " << y << ")" << endl;

        }

};

 

int main(void)

{

        int i;

        CPoint ary[5] = { CPoint(1, 2), CPoint(3, 4), CPoint(5, 6) };

        CPoint sum;

 

        sum.SetXY(sum.GetSumX(ary, 5), sum.GetSumY(ary, 5));

 

        sum.Print();

        return 0;

}

 

[5.3]

/*

CPoint **ptr;가 있다.

이 포인터를 통해 2 3열의 CPoint 2차원 객체 배열을 동적으로 생성한다.

그리고 rand 함수를 사용하여 각 원소의 x, y 값을 임의의 값으로 채운 후 출력해 본다.

main 함수가 끝나기 전에 delete를 사용하여 동적으로 생성된 모든 객체의 메모리를 해제한다.

*/

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

 

class CPoint

{

private:

        int x;

        int y;

public:

        CPoint() :x(0), y(0)

        {

        }

        CPoint(int a, int b) :x(a), y(b)

        {

        }

        void SetXY(int a, int b)

        {

               x = a;

               y = b;

        }

        void Print()

        {

               cout << "(" << x << ", " << y << ")" << endl;

        }

};

 

int main(void)

{

        CPoint **ptr;

        srand((unsigned)time(NULL));

        ptr = new CPoint*[2];

        for (int i = 0; i < 2; i++)

        {

               ptr[i] = new CPoint[3];

        }

        for (int i = 0; i < 2; i++)

        {

               for (int j = 0; j < 3; j++)

               {

                       ptr[i][j].SetXY(rand() % 100 + 1, rand() % 100 + 1);

                       ptr[i][j].Print();

               }

        }

        for (int i = 0; i < 2; i++)

        {

               delete[]ptr[i];

        }

        delete ptr;

}

 

[5.4]

/*

다음 main 함수가 수행될 수 있도록 CPoint 클래스에 SetX SetY 멤버함수를 추가해 본다

*/

#include <iostream>

using namespace std;

 

class CPoint

{

private:

        int x;

        int y;

public:

        CPoint() :x(0), y(0)

        {

        }

        CPoint &SetX(int a)

        {

               x += a;

               return *this;

        }

        CPoint &SetY(int b)

        {

               y += b;

               return *this;

        }

        void Print()

        {

               cout << "(" << x << ", " << y << ")" << endl;

        }

};

 

int main(void)

{

        CPoint P1, P2;

 

        P1.SetX(3).SetY(4);

        P1.Print();

 

        P2.SetY(6).SetX(5);

        P2.Print();

 

        return 0;

}

 

[5.5]

/*

다음 main 함수가 수행될 수 있도록 CArray 클래스를 작성해 본다.

CArray 클래스는 멤버 변수로 int 배열(int ary[5])을 가지고 있다

*/

#include <iostream>

using namespace std;

 

class CArray

{

private:

        int ary[5];

public:

        CArray()

        {

               for (int i = 0; i < 5; i++)

                       ary[i] = 0;

        }

        int &GetElem(int i) //참조반환하지 않으면 상수형태이기 때문에 lvalue 오류

        {

               return ary[i];

        }

        CArray &Increase(int a)

        {

               ary[a] += 1;

               return *this;

        }

};

 

int main(void)

{

        int i;

        CArray Ary;

 

        for (i = 0; i < 5; i++)

               Ary.GetElem(i) = i;

 

        Ary.Increase(0).Increase(1).Increase(2).Increase(3).Increase(4);

 

        for (i = 0; i < 5; i++)

               cout << "Ary[" << i << "]" << Ary.GetElem(i) << endl;

 

        return 0;

}

 

[5.6]

/*

다음과 같은 CCircle 클래스를 만들어 본다.

CCIrcle 클래스는 중심(int x, y)과 반지름(double Radius)를 가지고 있다.

생성자는 3가지 종류가 존재하는데 매개변수가 없는 생성자는 중심과 반지름의 값을 (0, 0, 1)로 초기화하고,

매개변수가 2개인 생성자는 x, y 값을 매개변수 값으로 설정하고 반지름은 1로 설정한다.

세번째, 매개변수가 3개인 생성자는 각각 중심과 반지름의 값을 설정한다.

멤버 함수로는 GetArea Move 함수가 존재한다.

GetArea 함수는 매개변수가 없는 경우 현재 반지름(Radius) 값을 기반으로 원의 면적을 계산하여 반환하면 되고,

매개변수(double)가 있는 경우 매개 변수 값을 반지름으로 하여 원의 면적을 반환하면 된다

Move 함수는 2개의 매개 변수르 전달받아 각각 x, y 값을 해당 값만큼 이동한다.

마지막으로 Print 함수에서는 객체의 중심과 원의 면적을 출력한다

*/

#include <iostream>

using namespace std;

 

class CCircle

{

private:

        int x;

        int y;

        double radius;

public:

        CCircle() :x(0), y(0), radius(1)

        {

        }

        CCircle(int a, int b) :x(a), y(b), radius(1)

        {

        }

        CCircle(int a, int b, int c) :x(a), y(b), radius(c)

        {

        }

        double GetArea()

        {

               return radius * radius * 3.14;

        }

        double GetArea(double a)

        {

               return a*a*3.14;

        }

        void Move(int a, int b)

        {

               x += a;

               y += b;

        }

        void Print()

        {

               cout << "(" << x << ", " << y << ")" << ", " << radius << endl;

        }

};

 

int main(void)

{

        CCircle C1;

 

        cout << "원의 면적은" << C1.GetArea() << endl;

        cout << "반지름 3인 원의 면적은 " << C1.GetArea(3) << endl;

 

        cout << "기존 중심과 반지름" << endl;

        C1.Print();

        cout << "중심을 이동하면" << endl;

        C1.Move(1, 2);

        C1.Print();

        return 0;

}

 

[5.7]

/*

다음 프로그램의 문제점을 설명하고 수정해 본다.

, 현재 나와있는 멤버 변수 및 함수 외에는 따로 변수나 함수를 추가할 수 없다.

CPointArray 클래스는 3개의 원소를 갖는 CPoint 객체배열을 포함하고 있으며 18라인에서 생성자를 통해

(1, 1), (2, 2), (3, 3)으로 초기화하고 있다.

24라인의 SetSum 멤버 함수는 지정한 index의 원소 값(x, y)을 모든 원소들의 함으로 지정하는데 CPoint 클래스에 준비되어 있는

SetSum 함수를 호출하여 달성하고 있다.

이 때 CPoint 클래스는 6라인과 같이 CPointArray 객체를 참조로 받게 된다

*/

#include <iostream>

using namespace std;

 

class CPointArray; //전방선언

 

class CPoint

{

private:

        int x, y;

public:

        void SetSum(CPointArray &Pa);

        void Print()

        {

               cout << "(" << x << ", " << y << ")" << endl;

        }

 

        friend class CPointArray; //서로 friend 선언해주어야한다(private 멤버 접근 위해)

};

 

class CPointArray

{

private:

        CPoint Ary[3];

public:

        CPointArray()

        {

               for (int i = 0; i < 3; i++)

               {

                       Ary[i].x = i + 1;

                       Ary[i].y = i + 1;

               }

        }

        void SetSum(int index)

        {

               Ary[index].SetSum(*this);

        }

        void Print()

        {

               for (int i = 0; i < 3; i++)

                       Ary[i].Print();

        }

 

        friend class CPoint; //추가해줘야하는 문장

};

 

void CPoint::SetSum(CPointArray &Pa)

{

        x = (Pa.Ary[0].x + Pa.Ary[1].x + Pa.Ary[2].x);

        y = (Pa.Ary[0].y + Pa.Ary[1].y + Pa.Ary[2].y);

}

 

int main(void)

{

        CPointArray PAry;

 

        PAry.SetSum(0);

        PAry.Print();

        return 0;

}

 

[5.8]

/*

정사각형과 원을 동시에 표현할 수 있는 CShape 클래스를 만들어 본다.

CShape 클래스는 멤버 변수로 정사각형 또는 원을 의미하는 타입 변수를 가지고 있으며,

int형 변수 하나를 통해 정사각형의 경우 한변의 길이를 나타내고, 원의 경우 반지름을 나타내도록 한다.

생성자를 통해 타입과 한변의 길이(반지름)를 지정할 수 있으며, 멤버 함수로는 각 도형의 면적을 계산하는 GetArea함수가 있다.

*/

#include <iostream>

using namespace std;

 

class CShape

{

private:

        int type;

        int len; //. 혹은 반지름

        double const PI;

        static int rectCount;

        static int circCount;

public:

        CShape():PI(3.14)//포인터를 위한 생성자

        {

               rectCount++;

        }

        CShape(int t, int num) :type(t), len(num), PI(3.14)

        {

               if (t == 1)

                       rectCount++;

               else if (t == 2)

                       circCount++;

        }

        ~CShape()

        {

               rectCount--;

        }

        static int GetRectCount()

        {

               return rectCount;

        }

        static int GetCircleCount()

        {

               return circCount;

        }

        double GetArea()

        {

               int t = type;

               if (t == 1)

               {

                       return (len*len);

               }

               else if (t == 2)

               {

                       return (PI*len*len);

               }

               else

               {

                       cout << "잘못된 타입을 입력하였습니다" << endl;

               }

        }

};

 

int CShape::rectCount = 0;

int CShape::circCount = 0;

 

int main(void)

{

        CShape S1(1, 5); //정사각형

        CShape S2(2, 5); //

        CShape *pRect = new CShape[3]; //디폴트로 정사각형

 

        cout << "사각형 개수: " << CShape::GetRectCount() << endl;

        cout << "원 개수: " << CShape::GetCircleCount() << endl;

        cout << "S1의 면적: " << S1.GetArea() << endl;

 

        delete[]pRect;

 

        cout << "사각형 개수:" << CShape::GetRectCount() << endl;

        cout << "원 개수: " << CShape::GetCircleCount() << endl;

        cout << "S2의 면적: " << S2.GetArea() << endl;;

        return 0;

}

 


개발 환경:Visual Studio 2017


지적, 조언, 질문 환영입니다! 댓글 남겨주세요~


[참고] 기초를 탄탄히 세워주는 C++ 프로그래밍 입문 황준하 저

반응형