C++中的名字隐藏之<C++编程思想>

 <C++编程思想>第14.5小节中提到了名字隐藏,感觉挺有意思,在这里以自己的语言叙述如下。

假如有如下的基类Base,具体定义如下:

 1 class Base {
 2     public:
 3 
 4         int f() const {
 5             std::cout << "Base::f()" << std::endl;
 6         }
 7         
 8         int f(const std::string& str) {
 9             std::cout << "Base::f(string) " << str << std::endl;
10             return 1;
11         }
12 
13         void g() {
14             std::cout << "Base::g()" << std::endl;
15         }
16 
17     private:
18 };
Base Definition

派生类Derived1继承自Base,定义如下:

1 class Derived1 : public Base {
2     public:
3         void g() const {
4             std:;cout << "Derived1::g()" << std::endl;
5         }
6     private:
7 };
Derived1 Definition

派生类Derived2继承自Base,定义如下:

1 class Derived2 : public Base {
2     public:
3         int f() const {
4             std::cout << "Derived2::f()" << std::endl;
5             return 2;
6         }
7     private:
8 };
Derived2 Definition

其中在Derived2中,对基类成员函数f()进行了重定义。
派生类Derived3继承自Base,定义如下:

1 class   Derived3 : public Base {
2     public:
3         void  f()  const {
4             std::cout << "Derived3::f()" << std::endl;
5         }
6     private:
7         
8 };
Derived3 Definition

在Derived3中,修改了基类Base成员函数f()的返回类型。
派生类Derived4继承自Base,定义如下:

1 class  Derived4 : public  Base {
2     public:
3         int f(int  p) const {
4             std::cout << "Derived4::f() "  << p << std::endl;
5         }
6     private:
7 };
Derived4 Definition

 在Derived4中,修改了基类Base成员函数f(string)的参数类型。

 1 int  main(int argc, char* argv[]) {
 2 
 3     std::string str("Hello");
 4     Derived1 d1;
 5     //call the function void g() const in Derived1;
 6     //the function void g() in class Base is hidden.
 7     d1.g();
 8  
 9     //call the function in class Base.
10     d1.f();
11     d1.f(str);
12 
13     Derived2 d2;
14     //call the function int f() const in class Derived2.
15     //the version in class Base is hidden.
16     d2.f();
17 
18     // error! function int f(string) const in class Base is hidden.
19     //d2.f(str); 
20 
21 
22     Derived3 d3;
23     //call the version void f() const in class Derived3.
24     //functions int f() cosnt and int f(string) const are all hidden.
25     d3.f()
26     
27     //error!
28     //d3.f(str);
29 
30 
31     Derived4 d4;
32     d4.f(2);
33 
34     //error!
35     //d4.f();
36     //d4.f(str);
37 }
main

 执行main函数中的代码,验证了C++中存在的名字隐藏。

1. 为什么C++中会存在此种类型的名字隐藏?设计此类隐藏的目的是什么?

按照书上P344的提法:“如果通过修改基类中一个成员函数的操作与/或返回类型来改变基类的接口”

原文地址:https://www.cnblogs.com/miaoyong/p/3085500.html