Item 33: Avoid hiding inherited names(Effective C++)

Names in derived classes hide names in base classes. Under public inheritance, this is never desirable.

To make hidden names visible again, employ using declarations or forwarding functions.

 1  #include  < iostream >
 2  using   namespace  std;
 3 
 4  class  Base
 5  {
 6       private :
 7           int  x;
 8 
 9       public :
10           virtual   void  mf1()  =   0 ;
11           virtual   void  mf1( int )
12          {
13              cout  <<   " mf1(int) in base "   <<  endl;
14          }
15 
16           virtual   void  mf2()
17          {
18              cout  <<   " mf2 in base "   <<  endl;
19          }
20 
21           void  mf3()
22          {
23              cout  <<   " mf3 in base "   <<  endl;
24          }
25 
26           void  mf3( double )
27          {
28              cout  <<   " mf3(double) in base "   <<  endl;
29          }
30  };
31 
32  class  Derived:  public  Base 
33  {
34       public :
35           using  Base::mf1;        //  make all things in Base named mf1 and mf3
36           using  Base::mf3;        //  visible (and public) in Derived's scope
37 
38           virtual   void  mf1()
39          {
40              cout  <<   " mf1 in derived "   <<  endl;
41          }
42          
43           void  mf3()
44          {
45              cout  <<   " mf3 in derived "   <<  endl;
46          }
47          
48           void  mf4()
49          {
50              cout  <<   " mf4 in derived "   <<  endl;
51          }
52  };
53 
54 
55 
56  int  main()
57  {
58      Derived d;
59 
60       int  x  =   0 ;
61      d.mf1();                  //  still fine, still calls Derived::mf1
62 
63      d.mf1(x);                 //  now okay, calls Base::mf1
64 
65      d.mf2();                  //  still fine, still calls Base::mf2
66 
67      d.mf3();                  //  fine, calls Derived::mf3
68 
69      d.mf3(x);                 //  now okay, calls Base::mf3
70 
71      cin. get ();
72 
73       return   0 ;
74  }

转载于:https://www.cnblogs.com/zhtf2014/archive/2011/04/02/2002963.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值