命名空间
变体
操作

派生类

来自 cppreference.cn
< cpp‎ | 语言
 
 
C++ 语言
 
 

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

目录

[编辑] 语法

基类列表在 类声明语法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 可以以任何顺序出现。
属性 - (C++11 起) 任意数量的属性序列
access-specifier - 以下之一:privatepublicprotected
class-or-computed - 以下之一
  • nested-name-specifier (可选) type-name
  • nested-name-specifier template simple-template-id
(C++11 起)
(C++26 起)

由于语法限制,elaborated type specifier 不能直接作为 class-or-computed 出现。

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

声明为 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::iostreamstd::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 成员访问说明符 从基类派生时,基类的所有公有和保护成员都可作为派生类的保护成员访问(基类的私有成员除非是友元,否则永远不可访问)。

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

[编辑] 私有继承

当一个类使用 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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
CWG 1710 C++98 class-or-decltype 的语法使得无法从
需要 template 消歧符的从属类派生
允许 template

[编辑] 参阅