c++重载基类函数

https://stackoverflow.com/questions/15499146/why-a-derived-class-must-redefine-an-overrided-base-class-method

    •  

      Your foo(int) hides the base class name. Fix it like this:

      class Derived: public Base { public: using Base::foo; void foo(int i) { } void test() { foo(); foo(1); } }; 
       
    • thanks a lot, it works! But I still don't understand why we need this using clause. but it's ok – armand bendanan Mar 19 '13 at 13:01
    •   Well, basically, it's because of the standard. A name explicitely declared in the derived "namespace" supersedes the implicitly inherited name(s). This is the whole reason. – sehe Mar 19 '13 at 13:13

下面的回答讲为什么不能重载:

The answer, as others have already said, is that the foo in the derived type hides the foo in the base type. To extend a bit on what that means the problem is that lookup has a set of rules, and the compiler must apply those rules until it finds the identifier. Once it finds the name, it won't continue looking for better matches, it will try to use what it sees.

When inside Derived::test you type foo(), the compiler must resolve foo, which might be anything (type, [member] variable, [member] function...). To do so it starts looking what is available inside Derived::test, and there is no foo declared there. It then widens the search to the full type Derived and it finds that there is a member function foo. At this point it stops *. If it had not find Derived::foo(int) it would keep expanding the search to the bases, then the namespace, then other namespaces...

* In this particular case, because the identifier resolves to a function an extra step is taken as ADL kicks in (or rather would kick in if there were arguments of non-fundamental types passed to the function).

猜你喜欢

转载自www.cnblogs.com/xiang-yin/p/12118320.html
今日推荐