C언어 가상함수(Shape 클래스)
너에게제공
534 0 0
class Shape
{
protected:
int x, y;
public:
Shape(int x=0, int y=0) { this->x = x; this->y = y;}
void setOrigin(int x, int y) { this->x = x; this->y = y; }
virtual void draw() { cout <<"Shape Draw" << endl; }
void printPosition() { cout << "x : " << x << ", y : " << y << endl; }
};
class Rectangle : public Shape
{
private:
int width, height;
public:
Rectangle (int x=0, int y=0, int w=5, int h=10) :Shape(x,y)
{
width=w;
height=h;
}
void setWidth(int w)
{
width=w;
}
void setHeight(int h)
{
height=h;
}
void draw()
{
cout<<"Rectangle draw"<<endl;
}
void printPosition()
{
Shape::printPosition();
cout<<"width:"<<width<<"height:"<<height<<endl;
}
};
class Circle : public Shape
{
private: int radius;
public: Circle(int x=0, int y=0, int r=5):Shape(x,y)
{
radius=r;
}
void setRadius(int r)
{
radius=r;
}
void draw()
{
cout<<"Circle draw"<<endl;
}
void printPosition()
{
Shape::printPosition();
cout<<"r:"<<radius;
}
};
int main()
{
Shape *ps = new Rectangle(); // 상향 형변환
ps->draw();
Shape *ps1 = new Circle(); // 상향형변환
ps1->draw();
delete ps;
delete ps1;
}
{
protected:
int x, y;
public:
Shape(int x=0, int y=0) { this->x = x; this->y = y;}
void setOrigin(int x, int y) { this->x = x; this->y = y; }
virtual void draw() { cout <<"Shape Draw" << endl; }
void printPosition() { cout << "x : " << x << ", y : " << y << endl; }
};
class Rectangle : public Shape
{
private:
int width, height;
public:
Rectangle (int x=0, int y=0, int w=5, int h=10) :Shape(x,y)
{
width=w;
height=h;
}
void setWidth(int w)
{
width=w;
}
void setHeight(int h)
{
height=h;
}
void draw()
{
cout<<"Rectangle draw"<<endl;
}
void printPosition()
{
Shape::printPosition();
cout<<"width:"<<width<<"height:"<<height<<endl;
}
};
class Circle : public Shape
{
private: int radius;
public: Circle(int x=0, int y=0, int r=5):Shape(x,y)
{
radius=r;
}
void setRadius(int r)
{
radius=r;
}
void draw()
{
cout<<"Circle draw"<<endl;
}
void printPosition()
{
Shape::printPosition();
cout<<"r:"<<radius;
}
};
int main()
{
Shape *ps = new Rectangle(); // 상향 형변환
ps->draw();
Shape *ps1 = new Circle(); // 상향형변환
ps1->draw();
delete ps;
delete ps1;
}