반응형
문제 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;
}
};
문제
다음 main() 함수가 실행되도록 Point 클래스를 상속받은 ColorPoint 클래스를 작성하고, 전체 프로그램을 완성하라.
int main() {
ColorPoint cp(5, 5, "RED");
cp.setPoint(10, 20);
cp.setColor("BLUE");
cp.show();
}
결과
BLUE색으로 ( 10, 20 )에 위치한 점입니다.
소스코드
#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 color;
public:
ColorPoint(int x, int y, string color);
void setPoint(int x, int y);
void setColor(string color);
void show();
};
ColorPoint::ColorPoint(int x, int y, string color) : Point(x, y) {
this->color = color;
}
void ColorPoint::setPoint(int x, int y)
{
move(x, y);
}
void ColorPoint::setColor(string color)
{
this->color = color;
}
void ColorPoint::show() {
cout << color << "색으로 ( " << getX() << ", " << getY() << " )에 위치한 점입니다." << endl;
}
int main() {
ColorPoint cp(5, 5, "RED");
cp.setPoint(10, 20);
cp.setColor("BLUE");
cp.show();
}
설명
원칙적으로 파생 클래스의 생성자를 작성할 떄, 기본 클래스의 생성자 중 하나를 선택해야 한다. 하지만 선택하지 않을 경우 컴파일러가 암묵적으로 기본 클래스의 기본 생성자를 호출하도록 컴파일한다. 그러므로 ColorPoint의 생성자를 선언 할 때 : Point(x, y) 을 선언해 주지 않으면 기본 생성자를 호출하려고 하며, Point의 기본생성자가 존재하지 않으므로 컴파일 오류가 난다.
반응형
'명품C++프로그래밍' 카테고리의 다른 글
명품 C++ Programming 실습문제 8장 5번 (2) | 2021.05.22 |
---|---|
명품 C++ Programming 실습문제 8장 4번 (0) | 2021.05.21 |
명품 C++ Programming 실습문제 8장 2번 (0) | 2021.05.21 |
명품 C++ Programming 실습문제 8장 1번 (0) | 2021.05.21 |
명품 C++ Programming 실습문제 7장 12번 (0) | 2021.05.21 |