一般情况下,我们希望使用私有(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/