蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

验证虚函数动态分派 vs 静态绑定、虚析构顺序、纯虚抽象类及对象切片现象

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-polymorphism.cpp
explore-cpp-polymorphism.cpp129 行
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

class Animal {
public:
    virtual std::string sound() const { return "Animal sound"; }
    virtual ~Animal() = default;
};

class Dog final : public Animal {
public:
    std::string sound() const override final { return "Dog barks"; }
};

class Cat : public Animal {
public:
    std::string sound() const override { return "Cat meows"; }
};

class NonVirtualAnimal {
public:
    std::string sound() const { return "Animal sound"; }
};

class NonVirtualDog : public NonVirtualAnimal {
public:
    std::string sound() const { return "Dog barks"; }
};

class TrackedBase {
public:
    std::vector<std::string>& log;
    explicit TrackedBase(std::vector<std::string>& l) : log(l) {}
    virtual std::string sound() const { return "Animal sound"; }
    virtual ~TrackedBase() { log.push_back("Animal destroyed"); }
};

class TrackedDog : public TrackedBase {
public:
    explicit TrackedDog(std::vector<std::string>& l) : TrackedBase(l) {}
    std::string sound() const override { return "Dog barks"; }
    ~TrackedDog() override { log.push_back("Dog destroyed"); }
};

class AbstractShape {
public:
    virtual double area() const = 0;
    virtual ~AbstractShape() = default;
};

class RectShape : public AbstractShape {
    double w_, h_;
public:
    RectShape(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_; }
};

class TriShape : public AbstractShape {
    double w_, h_;
public:
    TriShape(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_ / 2.0; }
};

int main() {
    // 1. Dynamic binding (virtual) vs static binding (non-virtual)
    Dog dog;
    Cat cat;
    Animal* ap = &dog;
    std::string dyn1 = ap->sound();
    ap = &cat;
    std::string dyn2 = ap->sound();

    NonVirtualDog nvd;
    NonVirtualAnimal* nv_ptr = &nvd;
    std::string stat1 = nv_ptr->sound();
    std::string direct1 = nvd.sound();

    std::string act1 = dyn1 + "|" + dyn2 + "|" + stat1 + "|" + direct1;
    const std::string exp1 = "Dog barks|Cat meows|Animal sound|Dog barks";
    bool ok1 = (act1 == exp1);

    // 2. Virtual destructor calls derived then base destructor
    std::vector<std::string> dtor_log;
    TrackedBase* poly = new TrackedDog(dtor_log);
    std::string voice = poly->sound();
    delete poly;
    std::string act2 = voice + "->" + dtor_log[0] + "->" + dtor_log[1];
    const std::string exp2 = "Dog barks->Dog destroyed->Animal destroyed";
    bool ok2 = (act2 == exp2);

    // 3. Pure virtual abstract class, reference binding, and final trait
    static_assert(std::is_abstract_v<AbstractShape>, "AbstractShape must be abstract");
    static_assert(std::is_final_v<Dog>, "Dog must be final");
    RectShape rec(10, 5);
    TriShape tri(10, 6);
    AbstractShape& s1 = rec;
    AbstractShape& s2 = tri;
    std::string act3 = "rect=" + std::to_string(static_cast<int>(s1.area())) +
                       ",tri=" + std::to_string(static_cast<int>(s2.area())) +
                       ",abs=1,final=1";
    const std::string exp3 = "rect=50,tri=30,abs=1,final=1";
    bool ok3 = (act3 == exp3);

    // 4. Object slicing by value vs polymorphism via reference
    Animal sliced = dog;
    Animal& ref = dog;
    std::string act4 = "sliced=" + sliced.sound() + "|ref=" + ref.sound();
    const std::string exp4 = "sliced=Animal sound|ref=Dog barks";
    bool ok4 = (act4 == exp4);

    std::cout << "{\n"
              << "  \"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\",\n"
              << "  \"cases\": [\n"
              << "    {\"name\": \"virtual_vs_static_dispatch\", \"expected\": \"" << exp1
              << "\", \"actual\": \"" << act1 << "\", \"passed\": " << (ok1 ? "true" : "false") << "},\n"
              << "    {\"name\": \"virtual_destructor_chain\", \"expected\": \"" << exp2
              << "\", \"actual\": \"" << act2 << "\", \"passed\": " << (ok2 ? "true" : "false") << "},\n"
              << "    {\"name\": \"pure_virtual_abstract_and_final\", \"expected\": \"" << exp3
              << "\", \"actual\": \"" << act3 << "\", \"passed\": " << (ok3 ? "true" : "false") << "},\n"
              << "    {\"name\": \"object_slicing_vs_reference\", \"expected\": \"" << exp4
              << "\", \"actual\": \"" << act4 << "\", \"passed\": " << (ok4 ? "true" : "false") << "}\n"
              << "  ]\n"
              << "}\n";
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-polymorphism-lab/explore-cpp-polymorphism.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-polymorphism.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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