本文共 2286 字,大约阅读时间需要 7 分钟。
15.5.3. Scope and Member Functions
A member function with the same name in the base and derived class behaves the same way as a data member: The derived-class member hides the base-class member within the scope of the derived class. The base member is hidden, even if the prototypes of the functions differ:
struct Base {
int memfcn();
};
struct Derived : Base {
int memfcn(int); // hides memfcn in thebase
};
Derived d; Base b;
b.memfcn(); // calls Base::memfcn
d.memfcn(10); // calls Derived::memfcn
d.memfcn(); // error: memfcn with noarguments is hidden
d.Base::memfcn(); // ok: callsBase::memfcn
d.memfcn();// error: Derived has no memfcn that takes no arguments
Toresolve this call, the compiler looks for the name memfcn, which it finds inthe class Derived.
Once the name is found, the compiler looks no further. This call does not matchthe definition of memfcnin Derived, which expects an intargument. The call providesno such argument and so is in error.
Beware:Recall that functions declared in a local scope do not overload functions defined at global scope. Similarly, functions defined in a derived class do not overload members defined in the base. When the function is called through a derived object, the arguments must match a version of the function defined in the derived class. The base class functions are considered only if the derived does not define the function at all.
Note:If the derived class redefines any of the overloaded members, then only the one(s) redefined in the derived class are accessible through the derived type.
If a derived class wants to make all the overloaded versions available through its type, then it must either redefine all of them or none of them.
Instead of redefining every base-class version that it inherits, a derived class can provide a using declaration (Section 15.2.5, p. 574) for the overloaded member. A using declaration specifies only a name; it may not specifya parameter list. Thus, a using declaration for a base class member function name adds all the overloaded instances of that function to the scope of the derived-class. Having brought all the names into its scope, the derived class need redefine only those functions that it truly must define for its type. It can use the inherited definitions for the others.
转载地址:http://oyyii.baihongyu.com/