C++ 模板:重载时找不到基类类型参数方法

C++ Template: cannot find base class type parameter method when overloaded

本文关键字:基类 类型参数 方法 找不到 模板 重载 C++      更新时间:2023-10-16

请考虑以下示例:

#include <iostream>
class Base {
public:
virtual void foo(std::string str) = 0;
void foo() { foo("LOL"); }
};
class Derived : public Base {
public:
void foo(std::string str) { std::cout << str << std::endl; }
};
template<class T> class MyTemplate {
public:
void print() { a.foo(); }
T a;
};
int
main(int argc, char** argv)
{
MyTemplate<Derived> a;
a.print();
}

编译时,出现以下错误:

main.cpp: In instantiation of ‘void MyTemplate<T>::print() [with T = Derived]’:
main.cpp:24:11:   required from here
main.cpp:16:18: error: no matching function for call to ‘Derived::foo()’
void print() { a.foo(); }
^
main.cpp:16:18: note: candidate is:
main.cpp:11:8: note: virtual void Derived::foo(std::string)
void foo(std::string str) { std::cout << str << std::endl; }
^
main.cpp:11:8: note:   candidate expects 1 argument, 0 provided

它发现解决方案是编写:

void print() { a.Base::foo(); } 

但这是为什么呢?为什么 G++ 自己找不到 Base::foo(( 方法?

谢谢

原因是类Derivedfoo的方法隐藏了从类Base继承的所有同名方法。因此,只有接受std::string作为参数的方法foo的单个版本可用于通过Derived调用。因此,您必须使用以下语法调用不接受任何参数的foo

a.Base::foo();

请注意,您还可以使用 using 声明使继承fooDerived类中可见:

class Derived : public Base {
public:
using Base::foo;
void foo(std::string str) { std::cout << str << std::endl; }
};

通过此更改,下一个代码将生效:

a.foo();