我想在基类中定义一个函数,在子类中定义一个具有相同名称和另一个签名的函数,如下所示:
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::foo
和 B::foo
具有相同的签名)。
关于c++ - 如何继承一些候选的多态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164122/