I want to know why there is an error in the following function:
#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;
}
I get an error " error C2660: 'Aba::f' : function does not take 0 arguments". But "aba" inherited from "saba" so he can use f() of "saba"
Aba::f
, which takes 1 parameter, hides the Saba::f
. That is why when you call Aba::f
with no argument the compiler complains. Just for your information clang gave me those warnings :
main.cpp:38:18: warning: 'Aba::f' hides overloaded virtual function [-Woverloaded-virtual]
virtual void f(int){ cout << "Aba f(int)" << endl; }
^
main.cpp:38:18: note: hidden overloaded virtual function 'Aba::f' declared here: different number of parameters (1 vs 0)
virtual void f(int){ cout << "Aba f(int)" << endl; }
I don't know what did you expect while writing your code but it works correctly.
During initialization you've casted pointer from Saba
to Aba
in:
Aba* abaPtr = dynamic_cast<Aba*>(sabaPtr);
So, abaPtr
is proper Aba
object (of course if dynamic cast was successfull). Next, in the line
abaPtr->f();
you are calling Aba::f(int)
which expects 1 argument to specified while you don't specify it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.