The C++ Programming Language,第 4 版,在 §20.5.2“访问基类”(第 605 页),它说(关于私有(private)继承):
private bases are most useful when defining a class by restricting the interface to a base so that stronger guarantees can be provided.For example, B is an implementation detail of Z .The Vector of pointers template that adds type checking to its Vector base from §25.3 is a good example.
不清楚 Bjarne Stroustrup 在这里想表达什么。如何通过将“接口(interface)”限制为基类来定义类?他所说的“更强的保证”是什么意思?
最佳答案
让我们举一个非常简单的例子:
// A simple class with a *public* member
class A
{
public:
int a;
};
// Use private inheritance
class B : private A
{
public:
int b;
};
// Use public inheritance
class C : public A
{
public:
int c;
};
// ...
B my_b;
my_b.a = 0; // Invalid, the member a is private due to the private inhericance
C my_c;
my_c.a = 0; // Valid, because the inheritance is public
private
继承限制 对基类成员的访问。即使 A::a
成员变量是 public
,由于 private
继承,它在子类 B
。
关于c++ - "The C++ Programming Language"中描述的私有(private)继承用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44543380/