我想知道为什么以下功能出错:

#include<iostream>

using namespace std;
class Saba

{

public:

    Saba(){ cout << "Saba Ctor" << endl; }

    Saba(const Saba& a){ cout << "Saba Copy Ctor" << endl; }

    ~Saba(){ cout << "Saba Dtor" << endl; }

    virtual void f(){ cout << "Saba f()" << endl; }

    virtual void g(){ cout << "Saba g()" << endl; }

    void h(){ cout << "Saba h()" << endl; }

};

class Aba : public Saba

{

public:

    Aba(){ cout << "Aba Ctor" << endl; }

    Aba(const Aba& a){ cout << "Aba Copy Ctor" << endl; }

    ~Aba(){ cout << "Aba Dtor" << endl; }

    virtual void g(){ cout << "Aba g()" << endl; }

    virtual void f(int){ cout << "Aba f(int)" << endl; }

    virtual void h(){ cout << "Aba h()" << endl; }

};

class Son : public Aba

{

public:

    Son(){ cout << "Son Ctor" << endl; }

    Son(const Son& a){ cout << "Son Copy Ctor" << endl; }

    ~Son(){ cout << "Son Dtor" << endl; }

    void f(){ cout << "Son f()" << endl; }

    void h(){ cout << "Son h()" << endl; }

};

int main()

{

    Saba* sabaPtr = new Son();

    Aba* abaPtr =dynamic_cast<Aba*>(sabaPtr);

    abaPtr->f();

    abaPtr->g();

    abaPtr->h();

    delete sabaPtr;

    return 0;

}


我收到一个错误“错误C2660:'Aba :: f':函数未采用0个参数”。但是“ aba”是从“ saba”继承的,因此他可以使用“ saba”的f()

最佳答案

带有1个参数的Aba::f隐藏Saba::f。这就是为什么当您不带任何参数调用Aba::f时,编译器会抱怨的原因。仅供参考,叮当声给了我这些警告:


  main.cpp:38:18:警告:“ Aba :: f”隐藏了重载的虚拟函数[-Woverloaded-virtual]


virtual void f(int){ cout << "Aba f(int)" << endl; }
             ^



  main.cpp:38:18:注意:此处声明了隐藏的重载虚拟函数'Aba :: f':参数数量不同(1 vs 0)


virtual void f(int){ cout << "Aba f(int)" << endl; }

10-08 03:48