class Shape {
public:
enum ShapeColor { Red, Green, Blue };
virtual void draw(ShapeColor color = Red)const = 0;
};
class Rectangle :public Shape {
public:
virtual void draw(ShapeColor color = Green)const = 0;
};
class Circle :public Shape {
public:
virtual void draw(ShapeColor color)const = 0;
};
Shape* ps; //静态类型为Shape*
Shape* pc = new Circle; //静态类型为Shape*
Shape* pr = new Rectangle; //静态类型为Shape*Shape* ps;
Shape* pc = new Circle;
Shape* pr = new Rectangle;
ps = pc; //ps的动态类型如今是Circle*
ps = pr; //ps的动态类型如今是Rectangle*Shape* ps;
Shape* pc = new Circle;
Shape* pr = new Rectangle;
pc->draw(Shape::Red); //调用Circle::draw(Shape::Red)
pr->draw(Shape::Red); //调用Rectangle::draw(Shape::Red)Shape* pr = new Rectangle;
pr->draw(); //调用的是Rectangle::draw(Shape::Red)
//Circle也是相同的道理
Shape* pc = new Circle;
pc->draw(); //调用的是Circle::draw(Shape::Red),
//而不是Circle::draw(Shape::Green)class Shape {
public:
enum ShapeColor { Red, Green, Blue };
virtual void draw(ShapeColor color = Red)const = 0;
};
class Rectangle :public Shape {
public:
virtual void draw(ShapeColor color = Red)const;
};
class Circle :public Shape {
public:
virtual void draw(ShapeColor color = Red)const;
};class Shape {
public:
enum ShapeColor { Red, Green, Blue };
void draw(ShapeColor color = Red)const { //因为是non-virtual函数,因此不建议派生类隐藏
doDraw(Red);
}
private:
//真正的工作在此处完成,派生类可以重写
virtual void doDraw(ShapeColor color)const = 0;
};
class Rectangle :public Shape {
private:
virtual void doDraw(ShapeColor color)const = 0;
};