C++之Name Hiding

  • 子类中重新定义父类函数(重定义、修改返回类型、修改参数),自动在子类中隐藏掉该函数的其他版本(重载函数)
  •  1 #include "stdafx.h"
    
     2 #include <iostream> 
    
     3 using namespace std; 
    
     4 
    
     5 class Base 
    
     6 { 
    
     7 public: 
    
     8     int f() const 
    
     9     {  
    
    10         cout << "int Base::f()"<<endl;  
    
    11         return 1;  
    
    12     } 
    
    13     int f(int) const 
    
    14     {
    
    15         cout << "int Base::f(int)"<<endl;
    
    16         return 1; 
    
    17     } 
    
    18 }; 
    
    19 
    
    20 class Derived1 : public Base 
    
    21 { 
    
    22 public: 
    
    23     // Redefinition: 
    
    24     int f() const 
    
    25     { 
    
    26         cout << "int Derived1::f()"<<endl;
    
    27         return 1;
    
    28     } 
    
    29 }; 
    
    30 
    
    31 class Derived2 : public Base 
    
    32 { 
    
    33 public: 
    
    34     // Change return type: 
    
    35     void f() const { cout << "void Derived2::f()"<<endl;} 
    
    36 }; 
    
    37 
    
    38 class Derived3 : public Base 
    
    39 { 
    
    40 public: 
    
    41     // Change argument list: 
    
    42     int f(double,int) const 
    
    43     {  
    
    44         cout << "int Derived3::f(double,int)"<<endl;  
    
    45         return 1;  
    
    46     } 
    
    47 }; 
    
    48 
    
    49 int main() 
    
    50 {
    
    51     int x = 0;
    
    52     
    
    53     Derived1 d1;
    
    54     x = d1.f();
    
    55     //x = d1.f(1);
    
    56 
    
    57     Derived2 d2;
    
    58     d2.f();
    
    59     //x = f();
    
    60     //x = f(1);
    
    61 
    
    62     Derived3 d3;
    
    63     x = d3.f(1.0,1);
    
    64     //x = f();
    
    65     //x = d3.f(1);
    
    66 
    
    67     return 0;
    
    68 }
  • 参考《Thinking in C++》

你可能感兴趣的:(name)