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

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

꾸준함. 2017. 6. 27. 12:02

[4.1]

/*

텔레비전을 클래스로 표현한다.

그리고 이 클래스로부터 객체를 생성하고 사용해 본다.

텔레비전을 표현하기 위해서는 브랜드, 가격, 제조회사, 제조일자 등의 속성이 필요하고

켜다, 끄다, 채널을 돌리다, 볼륨을 조정하다 등의 메서드가 필요하다.

이 외에도 필요한 속성과 메서드를 생각해보고 (예제 4.1)의 클래스와 같이 작성해 본다

*/

#include <iostream>

#include <cstring>

using namespace std;

 

class TV

{

        //4.1에서는 아직 public private을 정의하지 않았다

        char brand[20]; //브랜드

        int price; //가격

        char company[50]; //회사

        char date[10]; //날짜

 

        void TurnOn() //켜다

        {

        }

        void TurnOff() //끄다

        {

        }

        void SwitchChannel() //채널 돌리다

        {

        }

        void VolumeUp() //소리를 키우다

        {

        }

        void VolumeDown() //소리를 줄이다

        {

        }

};

 

[4.2]

/*

다음 프로그램의 문제점을 수정한 후 실행해 보도록 한다

#include <iostream>

using namespace std;

 

class SoccerTeam

{

        int PlayerNo[11];

        bool bPossess;

        int Score;

 

        void KickOff()

        {

               bPossess = true;

        }

        void Shoot()

        {

        }

public:

        void KickBall()

        {

        }

        void Pass()

        {

        }

private:

        char TeamName[20];

};

 

int main(void)

{

        SoccerTeam Red, Blue;

 

        Red.Score = 0;

        Blue.Score = 0;

        Red.KickOff();

        Red.Pass();

        Red.Shoot();

        return 0;

}

*/

#include <iostream>

using namespace std;

 

class SoccerTeam

{

private: //별도로 명시안할 경우 private이긴 하지만 명확히 하기 위해

        int PlayerNo[11];

        bool bPossess;

        int Score;

public:

        void Init() //새로 추가된 함수

        {

               Score = 0;

        }

        void KickOff()

        {

               bPossess = true;

        }

        void Shoot()

        {

        }

//public:

        void KickBall()

        {

        }

        void Pass()

        {

        }

private:

        char TeamName[20];

};

 

int main(void)

{

        SoccerTeam Red, Blue;

 

        //Red.Score = 0; private으로 선언된 멤버변수 초기화할 수 없다(별도의 Init함수 필요)

        //Blue.Score = 0;

        Red.Init();

        Blue.Init();

        Red.KickOff();

        Red.Pass();

        Red.Shoot();

        return 0;

}

 

[4.3]

/*

[예제 4.4]의 구조체를 class로 변경하고 실행해 본다.

그리고 Move 함수를 추가해 본다. Move 함수는 int형 변수 2개를 매개변수 a, b로 전달받아 x,y 좌표의 값을 각각 a,b 만큼씩 이동하는 것이다.

main 함수에서 Move 함수를 호출한 후 제대로 이동이 되는지 Print 함수를 통해 확인해 보도록 한다

*/

#include <iostream>

using namespace std;

 

class Point

{

private:

        int x;

        int y;

public:

        void SetXY(int a, int b)

        {

               x = a;

               y = b;

        }

        void Print()

        {

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

        }

        void Move(int a, int b)

        {

               x += a;

               y += b;

        }

};

 

int main(void)

{

        Point P1;

        P1.SetXY(3, 4);

        cout << "변경 전: ";

        P1.Print();

 

        P1.Move(2, 1);

        cout << "변경 후: ";

        P1.Print();

        return 0;

}

 


[4.4]

/*

CStudent라는 클래스를 만들어 본다. CStudent 클래스는 이름(char name[20]),

학번(int number), 나이(int age)를 저장하기 위한 멤버 변수를 포함하고 있다.

그리고 생성자와 멤버 변수의 값을 변경하기 위한 멤버 함수, 데이터를 출력하기 위한 멤버함수가 필요하다

*/

#include <iostream>

#include <cstring>

using namespace std;

 

class CStudent

{

private:

        char name[20];

        int number;

        int age;

public:

        CStudent(char *str, int num, int n)

        {

               strcpy(name, str);

               number = num;

               age = n;

        }

        CStudent()

        {

               strcpy(name, "noname");

               number = 0;

               age = 0;

        }

        void SetName(char *str)

        {

               strcpy(name, str);

        }

        void SetNumber(int num)

        {

               number = num;

        }

        void SetAge(int n)

        {

               age = n;

        }

        void Print()

        {

               cout <<  "이름: " << name << endl<< "나이: " << age << endl << "학번: " << number << endl;

        }

};

 

int main(void)

{

        CStudent St1("홍길동", 11111111, 25);

        CStudent St2;

 

        St1.Print();

        St2.Print();

 

        St2.SetName("이순신");

        St2.SetNumber(22222222);

        St2.SetAge(30);

 

        St2.Print();

        return 0;

}

 

[4.5]

/*

다음 프로그램의 출력 결과에 대해 설명해 본다

*/

#include <iostream>

using namespace std;

 

class CMyClass

{

private:

        int i;

public:

        CMyClass(int a)

        {

               i = a;

               cout << "생성자: " << i << endl;

        }

        ~CMyClass()

        {

               cout << "소멸자: " << i << endl;

        }

};

 

CMyClass M(0); //전역 객체, 제일 먼저 생성된다(제일 마지막으로 소멸된다)

 

void f(CMyClass LocalM) //함수

{

}

 

int main(void)

{

        CMyClass M1(1); //1 생성

        CMyClass M2[3] = { 2, 3, 4 }; //2, 3, 4 생성

        f(M2[2]); //'4'를 매개변수로 삼는 f 함수

        return 0; //생성한 순서의 역순으로 소멸된다

}

 

[4.6]

/*

다음 main 함수와 실행 결과를 참고하여 좌표(x,y)를 나타내는 CPoint 클래스를 만들어 본다.

매개 변수가 3개인 경우 x 값은 합으로, y 값은 곱으로 초기화하면 된다

*/

#include <iostream>

using namespace std;

 

class CPoint

{

private:

        int x;

        int y;

public:

        CPoint() //매개변수 없을 떄

        {

               x = 0;

               y = 0;

        }

        CPoint(int a) //하나일 때

        {

               x = a;

               y = a;

        }

        CPoint(int a, int b) //두개일 떄

        {

               x = a;

               y = b;

        }

        CPoint(int a, int b, int c) //세개일 때

        {

               x = a + b + c;

               y = a*b*c;

        }

        void Print()

        {

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

        }

        //디폴트 소멸자

};

 

int main(void)

{

        CPoint P1;

        CPoint P2(1);

        CPoint P3(2, 3);

        CPoint P4(4, 5, 6);

 

        P1.Print();

        P2.Print();

        P3.Print();

        P4.Print();

        return 0;

}

 

[4.7]

/*

연습문제 4.6에서 만든 모든 생성자를 멤버 초기화 구문을 사용하여 재작성해 본다

예제 4.13에서는 멤버 변수의 값을 형식매개 변수의 값으로 초기화하는 예만을 살펴보았다.

그러나 초기화 구문 사용시 초기화 값으로는 형식 매개 변수뿐만 아니라 상수 또는 수식도 사용할 수 있다.

*/

#include <iostream>

using namespace std;

 

class CPoint

{

private:

        int x;

        int y;

public:

        CPoint():x(0), y(0) //매개변수 없을 떄

        {

               //x = 0;

               //y = 0;

        }

        CPoint(int a):x(a), y(a) //하나일 때

        {

               //x = a;

               //y = a;

        }

        CPoint(int a, int b):x(a), y(b) //두개일 떄

        {

               //x = a;

               //y = b;

        }

        CPoint(int a, int b, int c):x(a+b+c), y(a*b*c) //세개일 때

        {

               //x = a + b + c;

               //y = a*b*c;

        }

        void Print()

        {

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

        }

        //디폴트 소멸자

};

 

int main(void)

{

        CPoint P1;

        CPoint P2(1);

        CPoint P3(2, 3);

        CPoint P4(4, 5, 6);

 

        P1.Print();

        P2.Print();

        P3.Print();

        P4.Print();

        return 0;

}

 


개발 환경:Visual Studio 2017


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


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

반응형