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

 

 

*******

posted @ 2022-02-07 16:52  htj10  阅读(21)  评论(0编辑  收藏  举报
TOP