Effective C++ 37. Never redefine a function's inherited default parameter value

本文探讨了C++中虚函数的动态绑定与默认参数的静态绑定特性,通过具体示例说明了如何避免由默认参数引起的派生类行为不一致问题,并提出了一种非虚接口(NVI)的设计模式来解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

virtual functions are dynamically bound , but default parameters are statically bound.

class Shape {
public:
    enum ShapColor (Red, Green, Blue);
    virtual void draw(ShapeColor color = Red) const = 0;
};

class Rectangle: public Shape {
public:
    virtual void draw(ShapeColor color = Green) const;
};
Shape *pr = new Rectangle;

the default parameter value for this function call is taken from the Shape class, not the Rectangle class!

avoid confusion
I.

class Shape {
public:
    enum ShapColor (Red, Green, Blue);
    virtual void draw(ShapeColor color = Red) const = 0;
};

class Rectangle: public Shape {
public:
    virtual void draw(ShapeColor color = Red) const;
};
Shape *pr = new Rectangle;

but if the default paramter value is changed in Shape, all derived classes that repeat it most also be changed.

II. NVI idiom(non-virtual interface )

class Shape{
public:
    enum ShapeColor{ Red, Green, Blue };
    void draw(ShapeColor color = Red) const {
        doDraw(color);
    }
private:
    virtual void doDraw(color) const = 0;
};

class Rectangle: public Shape {
public:

private:
    virtual void doDraw(ShapeColor color) const;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值