条款37:绝不重新定义继承而来的缺省参数值。【Effective C++ (第三版)】
*******
class Shape { public: enum ShapeColor { RED, GREEN, BLUE }; //RED, GREEN, BLUE 分别对应 0 1 2 virtual void draw(ShapeColor color = ShapeColor::RED) { cout << "Shape::draw()\n"; cout << color << endl; } }; class Rectangle : public Shape { public: virtual void draw(ShapeColor color = ShapeColor::GREEN) { cout << "Rectangle::draw()\n"; cout << color << endl; } }; class Circle : public Shape { public: virtual void draw(ShapeColor color = ShapeColor::BLUE) { cout << "Circle::draw()\n"; cout << color << endl; } }; int main() { Shape* ps = 0; Shape* pR = new Rectangle(); Rectangle* pR2 = new Rectangle(); pR->draw();//输出 0 即 red --> 导致“调用子类的函数,却使用的是基类的缺省值”,不合理 pR2->draw();//输出 1 即 green /* Rectangle::draw() 0 Rectangle::draw() 1 */ system("pause"); return 0; }
class Shape { public: enum ShapeColor { RED, GREEN, BLUE }; //RED, GREEN, BLUE 分别对应 0 1 2 void draw(ShapeColor color = ShapeColor::RED) // non-virtual 函数 { doDraw(color); } private: virtual void doDraw(ShapeColor color) = 0; }; class Rectangle : public Shape { public: //... private: virtual void doDraw(ShapeColor color) { cout << "Rectangle::draw()\n"; cout << color << endl; } }; class Circle : public Shape { public: //... private: virtual void doDraw(ShapeColor color) { cout << "Circle::draw()\n"; cout << color << endl; } };
*******
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。