C++ 继承具有不同默认参数值的函数

C++ inherit a function with different default argument values

我想继承一个成员函数而不重新定义它,但给它不同的默认值。我该怎么办?

class Base{
  public:
    void foo(int val){value=val;};
  protected:
    int value;
};

class Derived : public Base{
  public:
    void foo(int val=10);
};

class Derived2 : public Base{
  public:
    void foo(int val=20);
};

void main(){
   Derived a;
   a.foo();//set the value field of a to 10
   Derived2 b;
   b.foo();//set the value field of b to 20
}

不要使用默认值,使用重载:

class Base{
    public:
        virtual void foo() = 0;

    protected:
        void foo(int val) { value = val; }

    private:
        int value;
};

class Derived : public Base {
    public:
        void foo() override { Base::foo(10); }
};

class Derived2 : public Base {
    public:
        void foo() override { Base::foo(20); }
};

override修饰符是C++11。

您必须重新定义它 — 没有其他方法可以指定不同的默认参数。但是您可以通过调用基本版本来简化实现:

class Base{
  public:
    void foo(int val){value=val;};
  protected:
    int value;
};

class Derived : public Base{
  public:
    void foo(int val=10) { Base::foo(val); }
};

class Derived2 : public Base{
  public:
    void foo(int val=20) { Base::foo(val); }
};

在 Scott Meyers 的 "Effective C++" 中有一章叫做 "Never redefine a function's inherited default parameter value"。你真的不应该。你可以阅读关于如果你这样做会发生的所有恐怖的非常令人信服的解释的章节。

不,你不能。但是你可以这样实现。

class Base{
public:
    virtual int getDefaultValue() = 0;
    void foo(){value = getDefaultValue();};
protected:
    int value;
};

class Derived : public Base{
public:
    int getDefaultValue() {
        return 10;
    }
};

class Derived2 : public Base{
public:
    int getDefaultValue() {
        return 20;
    }
};