代码之家  ›  专栏  ›  技术社区  ›  swongu

C++重载函数问题

  •  0
  • swongu  · 技术社区  · 16 年前

    为什么编译器找不到基类函数签名?改变 foo( a1 ) B::foo( a1 ) 作品。

    代码:

    class A1 ;
    class A2 ;
    
    class B
    {
    public:
       void foo( A1* a1 ) { a1 = 0 ; }
    } ;
    
    class C : public B
    {
    public:
       void foo( A2* /*a2*/ )
       {
          A1* a1 = 0 ;
          foo( a1 ) ;
       }
    } ;
    
    int main()
    {
       A2* a2 = 0 ;
       C c ;
       c.foo( a2 ) ;
       return 0 ;
    }
    

    编译器错误(VS2008):

    error C2664: 'C::foo' : cannot convert parameter 1 from 'A1 *' to 'A2 *'
    Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   James McNellis    8 年前

    名字 C::foo 阴影 名字 B::foo . 一旦编译器找到匹配的 foo 在C类中,它停止进一步搜索。

    您可以通过添加以下内容来解决问题:

    using B::foo;
    

    到类C的主体,或者通过重命名类B中的函数。