我有一个基类Circle
(简单地画圆圈)和两个派生类:Smiley
和Frowny
,添加两个独特的特征,分别是“嘴部表情”和“眼睛”。这两个类添加了新功能,重写了函数 draw_lines()
1 ,其原始函数位于 Circle
中。
// class Smiley
class Smiley: public Circle{
public:
Smiley(Point c, int rr) : Circle(c,rr), r(rr) { }
void draw_lines() const;
private:
int r;
};
void Smiley::draw_lines() const{
if (color().visibility())
// add the mouth
fl_arc(point(0).x + r/2, point(0).y + r/2, r, r, 180, 360);
// add the eyes
fl_arc(point(0).x + r/2, point(0).y + r/4, r/2, r/2, 0, 360);
fl_arc(point(0).x + 3/2 * r, point(0).y + r/4, r/2, r/2, 0, 360);
// the below is the body of the original function in Circle
if (color().visibility())
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
}
// class Frowney
class Frowny: public Circle{
public:
Frowny(Point c, int rr) : Circle(c,rr), r(rr) { }
void draw_lines() const;
private:
int r;
};
void Frowny::draw_lines() const{
if (color().visibility())
// add the mouth
fl_arc(point(0).x + r/2, point(0).y + r, r, r, 0, 180);
// add the eyes
fl_line(point(0).x + r/2 - 5, point(0).y + r/2, point(0).x + r, point(0).y + r/4);
fl_line(point(0).x + r + 5, point(0).y + r/4, point(0).x + 1.5*r, point(0).y + r/2);
if (color().visibility())
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
}
现在,应该从类 Smiley
和 Frowny
派生两个新类,为每个类添加特定的单独功能。
// class SmileHat
class SmileHat: public Smiley{
public:
SmileHat(Point c, int rr) : Smiley(c, rr), r(rr), center(c) { }
void draw_line() const;
private:
int r;
Point center;
};
与Frowny
类似,唯一的区别在于帽子的形状。
问题:
向每个类 Smiley
和 Frawney
添加新功能的标准做法是什么:
1.(再次)覆盖已经存在的(继承的)函数draw_lines()
并包含新功能?
void SmileHat::draw_line() const{
if (color().visibility())
// add triangle hat
fl_line(center.x - r, center.y + r/2, center.x , center.y + r);
fl_line(center.x + r, center.y + r/2, center.x, center.y + r);
// body of the function override in Smiley
if (color().visibility())
// add the mouth
fl_arc(point(0).x + r/2, point(0).y + r/2, r, r, 180, 360);
// add the eyes
fl_arc(point(0).x + r/2, point(0).y + r/4, r/2, r/2, 0, 360);
fl_arc(point(0).x + 3/2 * r, point(0).y + r/4, r/2, r/2, 0, 360);
// the below is the body of the original function in Circle
if (color().visibility())
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
}
2.为新类创建一个新成员函数以添加新功能?
void add_hat() const{
// draw hat
}
3.还有其他更有效的方法吗?
注意:
我问这个问题时考虑了实现继承的概念,我似乎没有通过连续/重复地覆盖相同的函数并扩展它来利用它,即在每个派生类中是基类代码的显式拷贝,并添加了少量内容。
1。函数 draw_line()
是类 Circle
中的一个虚拟
函数。这就是为什么可以用派生类重写它。
最佳答案
draw_lines() 方法应声明为虚拟:
virtual void Smiley::draw_lines() const {
//draw smiley implementation here
}
重写draw_lines()并调用基本方法来绘制笑脸:
virtual void SmileHat::draw_lines() const{
Smiley::draw_lines(); //call base method to draw smiley
//do the hat drawing here
}
关于c++ - 如何向派生类添加功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808420/