0
请考虑以下的例子基类类型参数方法:C++模板:找不到当超载
#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()方法?
由于
因为'a.foo()'不带任何参数,但是您的派生类函数'foo()'将'string'作为参数。 –
@克劳斯我想这不是那个笨蛋...... –
@EdgarRokyan:叶普,你说得对。删除了评论和投票...谢谢 – Klaus