条款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; }
*******