c++ - "The C++ Programming Language"中描述的私有(private)继承用法

标签 c++ inheritance private-inheritance

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/

相关文章:

c++ - 用私有(private)基函数覆盖公共(public)虚函数?

c++ - 我如何等待由我的应用程序 Qt/C++ 启动的另一个应用程序启动的应用程序

c++ - 如何确定 STL 容器中的最后一个有效元素

C++调用父函数仅在使用指针时有效

inheritance - 如何继承 MFC 对话框?

java - 使用泛型在方法调用时从父级转换为子级

c++ - 私有(private)继承,返回对基类静态成员的引用

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

c++ - 二叉搜索树实现

c++ - 根据SSE特性调用不同的函数实现