C++

명품 C++ 8장 3번 4번

NUMERO_K 2018. 11. 4. 17:50

문제 3~4에 적용 되는 2차원 상의 한 점을 표현하는 Point 클래스가 있다.


class Point {
    int x, y;
public:
    Point(int x, int y) { this->x = x; this->y = y; }
    int getX() { return x; }
    int getY() { return y; }
protected:
    void move(int x, int y) { this->x = x; this->y = y; }
};


3. 다음 main() 함수가 실행되도록 Point 클래스를 상속받은 ColorPoint 클래스를 작성하고, 전체 프로그램을 완성하라.


소스코드


#include <iostream>
#include <string>
using namespace std;
class Point {
    int x, y;
public:
    Point(int x, int y) { this->x = x; this->y = y; }
    int getX() { return x; }
    int getY() { return y; }
protected:
    void move(int x, int y) { this->x = x; this->y = y; }
};
class ColorPoint : public Point {
    string name;
public:
    ColorPoint(int x, int y, string name) : Point(x, y) { this->name = name; }
    void setPoint(int x, int y) { move(x, y); }
    void setColor(string name) { this->name = name; }
    void show() { cout << name << "색으로 (" << getX() << "," << getY() << ")에 위치한 점입니다." << endl; }
};
int main() {
    ColorPoint cp(5, 5, "RED");
    cp.setPoint(10, 20);
    cp.setColor("BLUE");
    cp.show();
}


실행결과



ColorPoint는 Point 의 파생 클래스이기때문에 생성자에서 Point 생성자로 매개변수를 넘겨줘야합니다.

x와 y 는 private 멤버이기 때문에 show 함수에서 getX getY 함수에서 리턴받아 출력합니다.


4. 다음 main() 함수가 실행되도록 Point 클래스를 상속받는 ColorPoint 클래스를 작성하고, 전체 프로그램을 완성하라.


소스코드


#include <iostream>
#include <string>
using namespace std;
class Point {
    int x, y;
public:
    Point(int x, int y) { this->x = x; this->y = y; }
    int getX() { return x; }
    int getY() { return y; }
protected:
    void move(int x, int y) { this->x = x; this->y = y; }
};
class ColorPoint : public Point {
    string name;
public:
    ColorPoint() : Point(0, 0) { name = "BLACK"; }
    ColorPoint(int x, int y) : Point(x, y) { name = "BLACK"; }
    void setPoint(int x, int y) { move(x, y); }
    void setColor(string name) { this->name = name; }
    void show() { cout << name << "색으로 (" << getX() << "," << getY() << ")에 위치한 점입니다." << endl; }
};
int main() {
    ColorPoint zeroPoint; // BLACK 색에 (0, 0) 위치의 점
    zeroPoint.show(); // zeroPoint를 출력한다.
    ColorPoint cp(5, 5);
    cp.setPoint(10, 20);
    cp.setColor("BLUE");
    cp.show(); // cp를 출력한다.
}


실행결과



3번과 같이 x,y가 Point 의 멤버이기 때문에, 생성자에서 Point 클래스의 생서자로 매개변수를 넘겨줘야합니다.