Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c++ - Inheritance and method overloading

Why C++ compiler gives this error? Why i can access lol() from B, but can not access rofl() [without parameters]. Where is the catch?

class A
{
public:
   void lol(void) {}
   void rofl(void) { return rofl(0);}
   virtual void rofl(int x) {}
};

class B : public A
{
public:
   virtual void rofl(int x) {}
};

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
   a.lol();
   a.rofl(1);
   a.rofl();

   B  b;
   b.lol();
   b.rofl(1);    
   b.rofl(); //ERROR -> B::rofl function does not take 0 arguments


   return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The B::rofl(int) 'hides' the A::rofl(). In order to have A's rofl overloads, you should declare B to be using A::rofl;.

class B : public A {
public: 
    using A::rofl;
    ...
};

This is a wise move of C++: it warns you that you probably also need to override the A::rofl() method in B. Either you do that, or you explicitly declare that you use A's other overloads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...