2017-08-08 68 views
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()方法?

由于

+0

因为'a.foo()'不带任何参数,但是您的派生类函数'foo()'将'string'作为参数。 –

+0

@克劳斯我想这不是那个笨蛋...... –

+0

@EdgarRokyan:叶普,你说得对。删除了评论和投票...谢谢 – Klaus

回答

1

的原因是,方法fooDerived类隐藏与从Base类继承的相同名称的所有方法。因此,仅接受std::string作为参数的方法foo的单一版本可用于通过Derived进行的呼叫。因此,你必须调用foo它不接受任何参数明确使用的语法:

a.Base::foo(); 

注意,你也可以使用using declaration作出继承foo可见Derived类:

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

有了这个更改下一个代码变得有效:

a.foo();