命名空间
变体
操作

派生类

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
range-for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 (在 C++17* 中弃用)
noexcept 说明符 (C++11)
异常
命名空间
类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储期说明符
初始化
 
 

任何类类型(无论是用 class-key class 还是 struct 声明)都可以声明为从一个或多个基类派生,而基类又可以从它们自己的基类派生,从而形成继承层次结构。

目录

[编辑] 语法

基类列表在 类声明语法base-clause 中提供。base-clause 由字符 : 后跟一个或多个 base-specifier 的逗号分隔列表组成。

attr (可选) class-or-computed (1)
attr (可选) virtual class-or-computed (2)
attr (可选) access-specifier class-or-computed (3)
attr (可选) virtual access-specifier class-or-computed (4)
attr (可选) access-specifier virtual class-or-computed (5)
1) 指定具有默认成员可访问性的非虚继承。
2) 指定具有默认成员可访问性的虚继承。
3) 指定具有给定成员可访问性的非虚继承。
4) 指定具有给定成员可访问性的虚继承。
5) 与 4) 相同,virtualaccess-specifier 可以以任何顺序出现。
attr - (自 C++11 起) 任意数量 属性 的序列
access-specifier - 之一:privatepublicprotected
class-or-computed - 之一:
  • nested-name-specifier (可选) type-name
  • nested-name-specifier template simple-template-id
(自 C++11 起)
(自 C++26 起)

详述类型说明符 由于语法限制,不能直接作为 class-or-computed 出现。

base-specifiers 在 base-clause 中可以是 包展开

final 声明的类或结构不能用 class-or-computed 表示。

(自 C++11 起)

如果省略 access-specifier,则对于用 class-key struct 声明的派生类,默认值为 public,对于用 class-key class 声明的派生类,默认值为 private

struct Base
{
    int a, b, c;
};
 
// every object of type Derived includes Base as a subobject
struct Derived : Base
{
    int b;
};
 
// every object of type Derived2 includes Derived and Base as subobjects
struct Derived2 : Derived
{
    int c;
};

base-clause 中列出的 class-or-computed 表示的类是直接基类。它们的基类是间接基类。同一个类不能多次指定为直接基类,但同一个类可以既是直接基类又是间接基类。

每个直接和间接基类都作为基类子对象存在于派生类的对象表示中,偏移量取决于 ABI。由于空基类优化,空基类通常不会增加派生对象的大小。基类子对象的构造函数由派生类的构造函数调用:可以在成员初始化列表中为这些构造函数提供参数。

[编辑] 虚基类

对于每个被指定为 virtual 的不同基类,最派生对象 仅包含该类型的一个基类子对象,即使该类在继承层次结构中出现多次(只要每次都以 virtual 继承)。

struct B { int n; };
class X : public virtual B {};
class Y : virtual public B {};
class Z : public B {};
 
// every object of type AA has one X, one Y, one Z, and two B's:
// one that is the base of Z and one that is shared by X and Y
struct AA : X, Y, Z
{
    AA()
    {
        X::n = 1; // modifies the virtual B subobject's member
        Y::n = 2; // modifies the same virtual B subobject's member
        Z::n = 3; // modifies the non-virtual B subobject's member
 
        std::cout << X::n << Y::n << Z::n << '\n'; // prints 223
    }
};

具有虚基类的继承层次结构的一个例子是标准库的 iostreams 层次结构:std::istreamstd::ostream 是使用虚继承从 std::ios 派生的。std::iostream 是从 std::istreamstd::ostream 派生的,因此 std::iostream 的每个实例都包含一个 std::ostream 子对象、一个 std::istream 子对象,以及只有一个 std::ios 子对象(以及,因此,一个 std::ios_base)。

所有虚基类子对象都在任何非虚基类子对象之前初始化,因此只有最派生类在其成员初始化列表中调用虚基类的构造函数

struct B
{
    int n;
 
    B(int x) : n(x) {}
};
 
struct X : virtual B { X() : B(1) {} };
struct Y : virtual B { Y() : B(2) {} };
struct AA : X, Y     { AA() : B(3), X(), Y() {} };
 
// the default constructor of AA calls the default constructors of X and Y
// but those constructors do not call the constructor of B because B is a virtual base
AA a; // a.n == 3
 
// the default constructor of X calls the constructor of B
X x;  // x.n == 1

当涉及虚继承时,类成员的非限定名称查找存在特殊规则(有时称为支配规则)。

[编辑] 公有继承

当类使用 public 成员访问说明符 从基类派生时,基类的所有公有成员都可作为派生类的公有成员访问,基类的所有保护成员都可作为派生类的保护成员访问(基类的私有成员永远不可访问,除非被友元)。

公有继承模拟了面向对象编程的子类型关系:派生类对象 IS-A 基类对象。期望派生对象的引用和指针可以被任何期望其任何公有基类的引用或指针的代码使用(参见 LSP),或者,在 DbC 术语中,派生类应维护其公有基类的类不变量,不应加强任何前置条件或弱化它重写的成员函数的任何后置条件。

#include <iostream>
#include <string>
#include <vector>
 
struct MenuOption { std::string title; };
 
// Menu is a vector of MenuOption: options can be inserted, removed, reordered...
// and has a title.
class Menu : public std::vector<MenuOption>
{
public:
    std::string title;
 
    void print() const
    {
        std::cout << title << ":\n";
        for (std::size_t i = 0, s = size(); i < s; ++i)
            std::cout << "  " << (i + 1) << ". " << at(i).title << '\n';
    }
};
// Note: Menu::title is not problematic because its role is independent of the base class.
 
enum class Color { WHITE, RED, BLUE, GREEN };
 
void apply_terminal_color(Color) { /* OS-specific */ }
 
// THIS IS BAD!
// ColorMenu is a Menu where every option has a custom color.
class ColorMenu : public Menu
{
public:
    std::vector<Color> colors;
 
    void print() const
    {
        std::cout << title << ":\n";
 
        for (std::size_t i = 0, s = size(); i < s; ++i)
        {
            std::cout << "  " << (i + 1) << ". ";
            apply_terminal_color(colors[i]);
            std::cout << at(i).title << '\n';
            apply_terminal_color(Color::WHITE);
        }
    }
};
// ColorMenu needs the following invariants that cannot be satisfied
// by publicly inheriting from Menu, for example:
// - ColorMenu::colors and Menu must have the same number of elements
// - To make sense, calling erase() should remove also elements from colors,
//   in order to let options keep their colors
// Basically every non-const call to a std::vector method will break the invariant
// of the ColorMenu and will need fixing from the user by correctly managing colors.
 
int main()
{
    ColorMenu color_menu;
 
    // The big problem of this class is that we must keep ColorMenu::Color
    // in sync with Menu.
    color_menu.push_back(MenuOption{"Some choice"});
 
    // color_menu.print(); // ERROR! colors[i] in print() is out of range
 
    color_menu.colors.push_back(Color::RED);
 
    color_menu.print(); // OK: colors and Menu has the same number of elements
}

[编辑] 保护继承

当类使用 protected 成员访问说明符 从基类派生时,基类的所有公有和保护成员都可作为派生类的保护成员访问(基类的私有成员永远不可访问,除非被友元)。

保护继承可用于“受控多态性”:在 Derived 的成员以及所有进一步派生的类的成员中,派生类 IS-A 基类:在期望 Base 的引用和指针的地方可以使用 Derived 的引用和指针。

[编辑] 私有继承

当类使用 private 成员访问说明符 从基类派生时,基类的所有公有和保护成员都可作为派生类的私有成员访问(基类的私有成员永远不可访问,除非被友元)。

私有继承通常用于基于策略的设计,因为策略通常是空类,并且将它们用作基类既可以实现静态多态性,又可以利用空基类优化

私有继承也可用于实现组合关系(基类子对象是派生类对象的实现细节)。使用成员可以提供更好的封装,并且通常是首选,除非派生类需要访问基类的保护成员(包括构造函数),需要重写基类的虚成员,需要基类在某些其他基类子对象之前构造并在之后析构,需要共享虚基类或需要控制虚基类的构造。在从形参包进行多重继承的情况下,或者当基类的标识在编译时通过模板元编程确定时,使用成员来实现组合也不适用。

与保护继承类似,私有继承也可用于受控多态性:在派生类的成员中(但不在进一步派生的类中),派生类 IS-A 基类。

template<typename Transport>
class service : private Transport // private inheritance from the Transport policy
{
public:
    void transmit()
    {
        this->send(...); // send using whatever transport was supplied
    }
};
 
// TCP transport policy
class tcp
{
public:
    void send(...);
};
 
// UDP transport policy
class udp
{
public:
    void send(...);
};
 
service<tcp> service(host, port); 
service.transmit(...); // send over TCP

[编辑] 成员名称查找

类成员的非限定和限定名称查找规则在名称查找中详细说明。

[编辑] 关键字

virtual

[编辑] 缺陷报告

以下行为变更缺陷报告已追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
CWG 1710 C++98 class-or-decltype 的语法使得不可能从以下类派生:
需要 template 消歧义符的依赖类
允许 template

[编辑] 参见