프로그래밍/C,C++

[명품 C++ programming]7,8,9장 실습문제

수학가형 2022. 1. 6. 17:35

단원:

7. 프렌드와 연산자 중복

8. 상속

9. 가상함수와 추상클래스

 

[실습 7.3]다음 연산을 통해 공짜 책인지를 판별하도록 !연산자를 작성하라.

코드:

#include<iostream>
using namespace std;
 
class Book
{
        string title;
        int price, pages;
public:
        Book(string title = "", int price = 0, int pages = 0)
        {
               this->title = title;
               this->price = price;
               this->pages = pages;
        }
        void show()
        {
               cout << title << ' ' << price << " " << pages << " 페이지" << endl;
        }
        string getTitle()
        {
               return title;
        }
 
        bool operator!();
};
 
//오퍼레이터 구현
bool Book::operator!()
{
        if (this->price == 0)
               return 1;
        else
               return 0;
}
 
//메인함수
int main()
{
        Book book("벼룩시장", 0, 50);
        if (!book)
               cout << "공짜다" << endl;
}

결과:

 

 

[실습 7.7]2차원 행렬을 추상화한 Matrix클래스를 활용하는 코드가 주어져 있다.

(a)<<,>> 연산자를 Matrix의 멤버함수로 구현하라.

(a)<<,>> 연산자를 Matrix의 프렌드 함수로 구현하라.

코드-a:

// <<연산자 정의
 
Matrix Matrix::operator<<(int x[4])
{
        for (int i = 0; i < 4; i++)
        {
               (this->element[i]) = x[i];
        }
 
        return *(this);
}


// >>연산자 정의
 
void Matrix::operator>>(int x[4])
{
        for (int i = 0; i < 4; i++)
        {
               x[i] = (this->element[i]);
        }
}

결과-a:

코드-b:

// <<연산자 정의
 
Matrix operator<<(Matrix& a, int x[4])
{
        for (int i = 0; i < 4; i++)
        {
               (a.element[i]) = x[i];
        }
 
        return a;
}

//  >>연산자 정의
 
void operator>>(Matrix a, int x[4])
{
        for (int i = 0; i < 4; i++)
        {
               x[i] = (a.element[i]);
        }
}

결과-b:

 

 

[실습 8.6]BaseArray 클래스를 상속받아 스택으로 작동하는 MyStack 클래스를 작성하라.

코드-헤더:

class BaseArray
{
private:
        int capacity;  //배열의 크기
        int* mem;  //정수 배열을 만들기 위한 메모리 포인터
protected:
        BaseArray(int capacity = 100)
        {
               this->capacity = capacity;
               mem = new int[capacity];
        }
        ~BaseArray()
        {
               delete[] mem;
        }
 
        void put(int index, int val)
        {
               mem[index] = val;
        }
        int get(int index)
        {
               return mem[index];
        }
        int getcapacity()
        {
               return capacity;
        }
};

코드-main():

#include <iostream>
#include"BaseArray.h"
using namespace std;
//basearray 클래스를 상속받아 스택으로 작동하는 MyStack 클래스 작성
/*
함수 push, length, pop, capacity 필요
*/
 
class MyStack : public BaseArray
{
        int stacksize = 0;  //일단 아무것도 없다고 가정하고 0으로 초기화
 
public:
        MyStack(int n) : BaseArray(n) {}  //Mystack 생성자는 기본 실행만 되고 실질적으로 basearray 생성자 실행
        void push(int n)
        {
               put(stacksize, n);  //부모 클래스의 mem 배열의 stacksize위치에 정수 n 삽입
               stacksize++;  //스택 사이즈를 1만큼 증가: stacksize 변수는 항상 공간을 의미하도록 코딩.
        }
        int length()
        {
               return stacksize;  //stacksize 변수가 공간을 의미하므로 stack 사이즈는 거기서 1 빼야 한다.
        }
        int pop()
        {
               stacksize--;  //stacksize 1만큼 감소시켜 유의미한 데이터를 의미하도록 변경
               return get(stacksize);  //stacksize 1 감소시킨 인덱스의 값을 리턴하므로서 pop 구현하며 감소된 stacksize 공간을 의미하는 인덱스가 된다.
        }
        int capacity()
        {
               return getcapacity();
        }
};
 
int main()
{
        MyStack mStack(100);
        int n;
        cout << "스택에 삽입할 5개의 정수를 입력하라>> ";
        for (int i = 0; i < 5; i++) {
               cin >> n;
               mStack.push(n); // 스택에 푸시
        }
        cout << "스택 용량:" << mStack.capacity() << ", 스택 크기:" << mStack.length() << endl;
        cout << "스택의 모든 원소를 팝하여 출력한다>> ";
        while (mStack.length() != 0) {
               cout << mStack.pop() << ' '; // 스택에서
        }
        cout << endl << "스택의 현재 크기 : " << mStack.length() << endl;
}

결과:

 

 

[실습 9.5]디지털 회로에서 기본적인 게이트로 OR, AND, XOR게이트 등이 있다. 이들은 각각 두개의 입력 신호를 받아 OR, AND, XOR 연산을 수행한 결과를 출력한다. 이 게이트들을 각각 클래스로 구현하고 클래스가 AbstractGate를 상속받도록 구현하라.

코드:

//논리게이트 작성
//AND게이트
class ANDGate :public AbstractGate
{
public:
    virtual bool operation()
    {
        if (x & y == 1)
            return 1;
        else
            return 0;
    }
   
};
 
//OR게이트
class ORGate :public AbstractGate
{
public:
    virtual bool operation()
    {
        if (x | y == 1)
            return 1;
        else return 0;
    }
};
 
//XOR게이트
class XORGate :public AbstractGate
{
public:
    virtual bool operation()
    {
        if (x ^ y == 1)
            return 1;
        else return 0;
    }
};

결과:


문제 소스:

책정보, 명품 C++ Programming : 네이버 책 (naver.com)

 

명품 C++ Programming

C++는 1979년 BJARNE STROUSTRUP에 의해 “C WITH CLASSES”라는 이름으로 시작되었지만, 지금은 시스템 소프트웨어, 응용 소프트웨어, 게임, 임베디드 소프트웨어, 모바일 프로그램 등 소프트웨어의 전 분

book.naver.com