问题描述
case 1:
class ObjectCount {
private:
ObjectCount(){}
};
class Employee : private ObjectCount {};
情况2:
class ObjectCount {
public:
ObjectCount(){}
};
class Employee : private ObjectCount {};
在case1:ObjectCount构造函数是私有的,继承是私有的。它给出编译器错误
In case1: ObjectCount constructor is private and inheritance is private . It gives compiler error
在case2:ObjectCount构造函数是公共的,继承是私有的。这段代码是确定。
In case2: ObjectCount constructor is public and inheritance is private . this code is ok.
任何人都可以解释这是怎么回事?
Can anyone explain how is it happening?
推荐答案
是理解什么是私人隐含:
First thing is understanding what is PRIVATE INHERITANCE:
私人继承是实现has-a关系的方法之一。使用私有继承,基类的公共和受保护成员成为派生类的私有成员。这意味着基类的方法不会成为派生对象的公共接口。但是,它们可以在派生类的成员函数内部使用。
Private Inheritance is one of the ways of implementing the has-a relationship. With private inheritance, public and protected members of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object. However, they can be used inside the member functions of the derived class.
私有构造函数只能从同一个类中访问。它不能从外部访问,甚至不能由派生类访问。
The Private Constructor can only be accessed from inside the same class. It cannot be accessed from the outside, not even by the derived classes.
这篇关于具有私有构造函数的类的私有继承的工作机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!