c++ - 转换到 child 时有没有办法使用 dynamic_cast ?

标签 c++ polymorphism dynamic-cast downcast

假设我有这些类(class):

struct Parent {};
struct Child : public Parent {
    void func() {}
};

现在说我想创建一个这样的函数:

void foo(Parent* arg) {
    auto child = dynamic_cast<Child*>(arg);

    if(child != nullptr) child->func();
}

但显然这显然会给我错误:

dynamic_cast: Parent is not a polymorphic type

所以我不能执行 dynamic_cast 这一步,有没有一种方法可以验证 arg 实际上是一个 Child*在运行时?

最佳答案

为您的 Parent 类提供一个虚函数。出于多种原因(例如通过基本 ptr 删除子项等),我们想到了析构函数。

关于c++ - 转换到 child 时有没有办法使用 dynamic_cast ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38125430/

相关文章:

c++ - 我应该如何区分子类

c++ - `std::pmr::monotonic_buffer_resource` : why the `dynamic_cast` ?

c++ - 在 C++ 中获取地址的内容

c++ - 为什么 std::vector 和 std::string 的比较运算符定义为模板函数?

c++ - 如何在directshow中叠加direct3d

c# - 操作系统设计问题 : File types associated with their appropriate programs

c++ - 为什么在 C++ 中将函数/方法重载称为静态多态性?

sql - 数据库中的多态性

c++ - dynamic_cast 的性能?

c++ - libsvm : C++ vs. MATLAB : What's With The Different Accuracies?