以下代码
#include <iostream>
template <class T>
class foo {
public:
T add(T x, T y) { return x + y; }
};
template <class T>
class bar : public foo<T> {
public:
T add(T x, T y, T z) {
T result;
result = this->add(x, y) + z;
return result;
}
};
int main() {
bar<int> a;
std::cout << a.add(1, 2, 3) << std::endl;
return 0;
}
出现以下错误:
b.cpp: In instantiation of ‘T bar<T>::add(T, T, T) [with T = int]’:
b.cpp:21:31: required from here
b.cpp:14:38: error: no matching function for call to ‘bar<int>::add(int&, int&)’
result = this->add(x, y) + z;
^
b.cpp:14:38: note: candidate is:
b.cpp:12:11: note: T bar<T>::add(T, T, T) [with T = int]
T add(T x, T y, T z) {
^
b.cpp:12:11: note: candidate expects 3 arguments, 2 provided
如果我将this->add(x, y)
替换为foo<T>::add
,或者将foo<T>::add
的名称更改为其他内容,例如foo<T>::addr
,则一切正常。如果没有名称冲突,为什么继承可以工作,但是当存在时,即使函数签名不同,它也不起作用?