蓝色天空.知识 · 实践 · 创造
我的收藏
C++ 教程目录 99章
课程介绍
C++ / LEARN BY DOING

C++ 继承

系统阐述 C++ 面向对象的 is-a 继承模型、基类与派生类语法、成员访问权限矩阵、public/protected/private 三种继承方式及多继承与虚继承消歧。

学完这一章,你能够

  • 系统阐述 C++ 面向对象的 is-a 继承模型、基类与派生类语法、成员访问权限矩阵、public/protected/private 三种继承方式及多继承与虚继承消歧。

继承的 is-a 语义与基类/派生类语法

继承允许基于已有类(基类)构建新类(派生类),在不重复编写已有成员的前提下复用逻辑并扩展专有行为。公有继承表达 `is-a` 关系——例如 `Dog` 是 `Animal` 的一种,既天然具备基类的 `eat()` 与 `sleep()`,又可扩展自身的 `bark()`。

派生类通过类派生列表声明:`class 派生类 : 访问修饰符 基类`。访问修饰符可为 `public`、`protected` 或 `private`,对 `class` 省略时默认为 `private`。例如 `Rectangle : public Shape` 可直接读取基类 `protected` 的 `width` 与 `height` 来计算面积(如 5×7=35)。

访问控制矩阵与不自动继承的特殊成员

基类成员的可见性由 `public`、`protected` 与 `private` 共同界定:派生类可以访问基类所有 `public` 和 `protected` 成员,但不能直接访问基类 `private` 成员(必须经由基类提供的公有或受保护接口间接操作),三类访问场景总结见下表。

派生类虽复用基类的多数成员,但有三类特殊成员不会按普通方法方式自动继承:一是基类的构造函数、析构函数与拷贝构造函数(C++11 可用 `using Base::Base;` 显式继承构造);二是基类的重载赋值运算符;三是基类的友元函数(友元关系不可传递也不被继承)。

三种继承类型、多继承与菱形虚继承

工程中绝大多数场景采用公有继承(`public`),此时基类 `public`/`protected` 成员在派生类中保持原有级别;保护继承(`protected`)会将基类 `public` 成员降级为 `protected`;私有继承(`private`)会将基类 `public` 与 `protected` 成员全部降为派生类的 `private`(常表达“依据某类实现”而非 `is-a`)。无论哪种继承,基类 `private` 成员都不可在派生类中直接访问。

C++ 支持多继承,派生列表以逗号分隔多个基类并分别指定继承方式,如 `class Rectangle : public Shape, public PaintCost` 同时复用几何尺寸与涂装单价计算(面积 35 对应花费 2450)。若多继承构成菱形层次导致共同基类出现两份副本,应使用虚继承(`virtual public Base`)确保最终派生类只保留唯一共享基类子对象。

类成员访问修饰符可见性矩阵

访问位置publicprotectedprivate
同一个类内部允许(yes)允许(yes)允许(yes)
派生类内部允许(yes)允许(yes)禁止直接访问(no)
类外代码 / 非友元类允许(yes)禁止(no)禁止(no)

验证单继承、三种继承访问边界、Shape+PaintCost 多继承及菱形虚继承

含完整源码 · 120 行
展开查看收起
cpp
#include <iostream>
#include <string>

class Animal {
public:
    std::string eat() const { return "eat"; }
    std::string sleep() const { return "sleep"; }
};

class Dog : public Animal {
public:
    std::string bark() const { return "bark"; }
};

class Shape {
public:
    void setWidth(int w) { width = w; }
    void setHeight(int h) { height = h; }
    int secretFactor() const { return secret_; }
protected:
    int width = 0;
    int height = 0;
private:
    int secret_ = 2;
};

class PaintCost {
public:
    int getCost(int area) const { return area * 70; }
};

class Rectangle : public Shape, public PaintCost {
public:
    int getArea() const { return width * height; }
    int scaledArea() const { return getArea() * secretFactor(); }
};

class ProtectedRect : protected Shape {
public:
    void configure(int w, int h) { setWidth(w); setHeight(h); }
    int area() const { return width * height; }
};

class PrivateRect : private Shape {
public:
    void configure(int w, int h) { setWidth(w); setHeight(h); }
    int area() const { return width * height; }
};

// Virtual inheritance resolving diamond ambiguity
class Device {
public:
    int id = 10;
};

class Scanner : virtual public Device {
public:
    void bumpScanner() { id += 5; }
};

class Printer : virtual public Device {
public:
    void bumpPrinter() { id += 7; }
};

class Copier : public Scanner, public Printer {};

int main() {
    // 1. Single public inheritance (Animal -> Dog & Shape -> Rectangle)
    Dog d;
    Rectangle r;
    r.setWidth(5);
    r.setHeight(7);
    std::string act1 = d.eat() + "+" + d.sleep() + "+" + d.bark() + "|area=" + std::to_string(r.getArea());
    const std::string exp1 = "eat+sleep+bark|area=35";
    bool ok1 = (act1 == exp1);

    // 2. Access control & public/protected/private inheritance
    ProtectedRect pr;
    pr.configure(4, 6);
    PrivateRect pvr;
    pvr.configure(3, 8);
    std::string act2 = "pub_priv_via_base=" + std::to_string(r.scaledArea()) +
                       ",prot=" + std::to_string(pr.area()) +
                       ",priv=" + std::to_string(pvr.area());
    const std::string exp2 = "pub_priv_via_base=70,prot=24,priv=24";
    bool ok2 = (act2 == exp2);

    // 3. Multiple inheritance (Shape + PaintCost)
    int area = r.getArea();
    int cost = r.getCost(area);
    std::string act3 = "area=" + std::to_string(area) + ",cost=" + std::to_string(cost);
    const std::string exp3 = "area=35,cost=2450";
    bool ok3 = (act3 == exp3);

    // 4. Virtual inheritance prevents duplicate base subobjects in diamond hierarchy
    Copier c;
    c.bumpScanner();
    c.bumpPrinter();
    bool single_base = (&static_cast<Scanner&>(c).id == &static_cast<Printer&>(c).id);
    std::string act4 = "id=" + std::to_string(c.id) + ",shared=" + (single_base ? "true" : "false");
    const std::string exp4 = "id=22,shared=true";
    bool ok4 = (act4 == exp4);

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"single_public_inheritance\", \"expected\": \"" << exp1
              << "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"inheritance_access_modes\", \"expected\": \"" << exp2
              << "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"multiple_inheritance_cost\", \"expected\": \"" << exp3
              << "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"virtual_inheritance_diamond\", \"expected\": \"" << exp4
              << "\", \"actual\": \"" << act4 << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    return 0;
}
在 G++ 13.3.0 C++17 离线容器中验证 Animal/Dog 与 Shape/Rectangle 单继承、public/protected/private 继承访问封装、多继承面积 35/花费 2450 及虚继承共享唯一 Device 子对象 4 项全通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2307.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2326.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

默认非虚继承下 `D` 对象内部会包含两份独立的 `A` 子对象,直接访问 `A` 成员时会产生二义性;将 `B` 与 `C` 改为 `virtual public A`(虚继承)即可让 `D` 仅保留唯一一份共享的 `A` 子对象。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习