如何继承一些多态函数的候选者?

时间:2016-10-20 20:39:41

标签: c++ inheritance polymorphism

我想在基类中定义一个函数,在子类中定义一个具有相同名称和另一个签名的函数,如下所示:

save2 "s" (C 1)

但它会导致编译错误:class A { public: void foo () {} }; class B : public A { public: void foo(int x) {} }; int main() { B b; b.foo(); } 。 如果我在B类中评论no matching function for call to ‘B::foo()’定义,它就会编译。 如何解决问题?

我真正想要的是在基类中定义多态接口并重新定义子类中的语义。

UPD:谢谢,答案适用于这个例子。但它似乎不适用于模板: sort.h

foo

TEST.CPP

...
class Sort {
public:
  template <typename TArr>
  static TArr& sort(TArr& array) { return sort(array, array.size()); }
};

class BubbleSort : public Sort { // add inheritance
public:
  using Sort::sort;
  template <typename TArr>
  static TArr& sort(TArr& array, size_t len) {
     ...
  }
};

当我跑步时,我得到:

...
int main () {
  ...
  std::array<int, 5> test_array {3, 2, 5, 1, 4};
  BubbleSort::sort(test_array)
  ...
}

为什么会这样?

UPD:知道了。

3 个答案:

答案 0 :(得分:2)

  

但它会导致编译错误:no matching function for call to ‘B::foo()’

尝试using-declaration

class A {
public:
    void foo() {}
};

class B : public A {
public:
    using A::foo;
    void foo(int x) {}
};
  

我真正想要的是在基类中定义多态接口并重新定义子类中的语义。

好吧,你应该让基类函数virtual在覆盖时具有相同的参数。否则,如何通过引用/指向基类的指针来调用子类函数?

答案 1 :(得分:2)

如果没有virtual,则A::foo()不会定义多态接口。

无论如何,您可以使用A::foo()声明通过B显示using

class B : public A {
public:
  using A::foo;
  void foo(int x) {}
};

这提供了多态性,你接受函数重载作为多态 - 即A::foo()B::foo()形成一个重载集,编译器根据参数选择调用哪个你传递(如果有的话),就像B包含两个重载函数一样(与现有A::fooB::foo具有相同的签名)。

答案 2 :(得分:1)

派生类中的函数f只是隐藏了基类中具有相同名称的所有函数。

要解决此问题,您可以使用using-declaration

class B : public A {
public:
  using A::foo;
  void foo(int x) {}
};