c++ - 如何继承一些候选的多态函数?

标签 c++ inheritance polymorphism

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

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

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

int main() {
  B b;
  b.foo();
}

但它会导致编译错误:no matching function for call to ‘B::foo()’。 如果我在 B 类中注释 foo 定义,它会编译。 如何解决问题?

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

UPD:谢谢,这个例子的答案有效。但它似乎不适用于模板: 排序.h

...
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) {
     ...
  }
};

测试.cpp

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

当我运行它时,我得到:

sort.h: In instantiation of ‘static TArr& Sort::sort(TArr&) [with TArr = std::array<int, 5ul>]’:
test.cpp:9:30:   required from here
sort.h:17:47: error: no matching function for call to ‘Sort::sort(std::array<int, 5ul>&, std::array<int, 5ul>::size_type)’
   static TArr& sort(TArr& array) { return sort(array, array.size()); }
                                               ^
sort.h:17:16: note: candidate: template<class TArr> static TArr& Sort::sort(TArr&)
   static TArr& sort(TArr& array) { return sort(array, array.size()); }
                ^
sort.h:17:16: note:   template argument deduction/substitution failed:
sort.h:17:47: note:   candidate expects 1 argument, 2 provided
   static TArr& sort(TArr& array) { return sort(array, array.size()); }

为什么会这样?

UPD:知道了。

最佳答案

没有virtual , A::foo()没有定义多态接口(interface)。

无论如何,你可以制作A::foo()通过 B 可见用using声明:

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

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

关于c++ - 如何继承一些候选的多态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164122/

相关文章:

java - 将功能注入(inject)两个没有公共(public)父类(super class)的类

enums - Rust-将特征包装在枚举中以用于内存布局和更简单的泛型?

c++ - 当 QFileDialog::getOpenFileName 窗口打开时,程序意外结束

c++ - std::getline( basic_istream<...> &&input, basic_string<...> &str ) 右值 -"input"

objective-c - 如何在 Swift 中更改覆盖函数返回类型

c++ - 重写采用继承结构的函数

java - 用多态替换条件

c++ - 嵌套模板的模板模板别名?

C++打印从字符串字符派生的整数

c++ - c++中虚继承是什么