c++ - 为什么要私下继承基类,还要名字publicizing?

标签 c++ private-inheritance

一般情况下,我们希望使用私有(private)继承来将实现细节隐藏到基类中。如果这是真的,

1) 为什么又出现了名称宣传功能?仅仅是为了语言的完整性还是有实际用途?

2) 即使我公开了基类函数名,派生类仍然可以声明另一个具有相同名称的函数。请考虑以下代码。

#include "iostream"
using namespace std;

class Base {
  public:
    int zoo;
    Base() {zoo =5;}
    int sleep() const {return 3;}
};

class Derived : Base { // Private inheritance
  public:
    using Base::zoo;
    using Base::sleep;
    int sleep() const { return 4.0; }
};

int main() {
    Derived der;
    der.sleep();
    cout<<" zoo is : "<<der.zoo<<endl;
    cout<<" Sleep is : "<<der.sleep()<<endl;
 }

在上面的代码片段中,即使我们公开了名称,我们仍然可以在派生类中声明名称,并且我们可以访问成员变量的基类版本。如何管理内存?

谢谢。

最佳答案

http://en.cppreference.com/w/cpp/language/using_declaration

If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

该链接提供了具体示例,具体说明了您正在做什么,并重申了我在上面引用的内容以及派生成员如何简单地隐藏基本成员。

关于c++ - 为什么要私下继承基类,还要名字publicizing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36994074/

相关文章:

c++ - CreateProcess() 函数无法运行。错误无法写入内存

c++ - 从 c++/c 中的函数返回的问题

c++ - 在 QtCreator 3.6 中运行两个应用程序

c++ - 如何转换为私有(private)派生的子类型?

c# - 如何在 C# 中使用 Private Inheritance aka C++ 以及为什么它不存在于 C# 中

c++ - 为什么 auto_ptr 似乎违反了 Visual C++ 上的私有(private)继承?

没有参数的 C++ 可变参数函数

c++ - 用于编译和运行 C++ 的 bash 脚本

c++ - 私有(private)继承和交换

c++ - 指向不可访问基中的成员函数的指针