正在加载...

继承

filesystem 页询问 note.txt 是否存在,并从 box.cpp 打印 pine。本页开始 Inheritance 模块。车间文件仍是 box.cpp。新工作命名父类型 Tag,其 show 打印 pine,再用 class Box : public Tag 声明子类型 Box。在 main 中构造 Box 并调用 b.show()。屏幕显示 pine。derived 细节留给下一页。
继承把子类型连到父类型,以便不复制成员即可复用。写带公有 show 的 class Tag,再写空体的 class Box : public Tag。保留 #include <iostream>。不要把 filesystem::exists 正文留在本页。构建仍熟悉:box.cpp 到 box。

在 main 上方写 Tag 与 Box : public Tag。在 main 中:Box b;、b.show();、return 0;。不要在 Box 里重写 show。
运行从 main 开始。b.show() 通过继承在 Tag 上找到 show 并打印 pine。一行:pine。

忘记 : public Tag 会导致构建失败。常见错误:名字写反、发明 extends、保留 filesystem 正文。本页停在 derived 之前。

打开 box.cpp。删除 filesystem exists 行。保留 iostream。声明 Tag 与 Box : public Tag。在 main 中构造 Box 并调用 show。

box.cpp Box inherits Tag show pine

cpp
#include <iostream>

class Tag
{
public:
    void show()
    {
        std::cout << "pine" << std::endl;
    }
};

class Box : public Tag
{
};

int main()
{
    Box b;
    b.show();
    return 0;
}

用 g++ -std=c++17 box.cpp -o box 重新构建并运行 ./box。屏幕显示 pine。若因 show 失败,检查 : public Tag。

📊 继承与屏幕显示

片段 屏幕显示
First pine,因为 Box 通过继承使用 Tag::show
Last pine,因为程序打印一次后返回
Rule class Box : public Tag 让 Box 调用写在 Tag 上的 show
Screen pine

每次只改一件事:临时在 Tag::show 打印 oak;恢复 pine。临时去掉 : public Tag;再加回。本页结束 inheritance,停在 derived 之前。一行:pine。

🧠 测试您的知识

准备开始

测试您的知识

通过这个互动测验挑战自己,看看你对这个主题的理解程度如何

❓
4
问题
🎯
70%
及格要求
♾️
∞
时间
🔄
∞
尝试次数

📝 说明

  • 仔细阅读每个问题
  • 为每个问题选择最佳答案
  • 您可以随时重新参加测验
  • 您的进度将显示在顶部