C++ 类作用域和函数成员

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值