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

函数重载和继承[重复]

  •  0
  • Bruce  · 技术社区  · 15 年前

    考虑一下代码:

    #include <stdio.h>
    
    class Base {
    public: 
        virtual void gogo(int a){
            printf(" Base :: gogo (int) \n");
        };
    
        virtual void gogo(int* a){
            printf(" Base :: gogo (int*) \n");
        };
    };
    
    class Derived : public Base{
    public:
        virtual void gogo(int* a){
            printf(" Derived :: gogo (int*) \n");
        };
    };
    
    int main(){
        Derived obj;
        obj.gogo(7);
    }
    

    出现此错误:

    >g++ -pedantic -Os test.cpp -o test
    test.cpp: In function `int main()':
    test.cpp:31: error: no matching function for call to `Derived::gogo(int)'
    test.cpp:21: note: candidates are: virtual void Derived::gogo(int*) 
    test.cpp:33:2: warning: no newline at end of file
    >Exit code: 1
    

    在这里,派生类的函数正在覆盖基类中所有同名(而不是签名)的函数。不知怎的,C++的这种行为看起来不太好。不是多态的。

    0 回复  |  直到 7 年前