从一个基类到另一个基类的多重继承[重复]

问题描述 投票:0回答:1

Assunme 我有一些抽象类 A。仅当 A 的动态类型是也继承自 B 的类时,我才想转换为其他类 B。有没有一种好的方法可以做到这一点,而不需要检查所有可能的情况中级课程(因为在我的实际场景中,有很多这样的课程)?

换句话说,是否有一些过程可以使下面的代码工作?

#include <memory>
#include <cassert>

struct A
{
    virtual void foo() = 0;
};

struct B
{
    virtual void bar() = 0;
};

struct C : public A, public B
{
    void foo() override {};
    void bar() override {};
};

struct D : public A
{
    void foo() override {};
};

int main()
{
    std::shared_ptr<A> a_ptr_1 = std::make_shared<C>();
    std::shared_ptr<A> a_ptr_2 = std::make_shared<D>();
    
    std::shared_ptr<B> b_ptr_1 = /* do something to a_ptr_1 */ nullptr;
    std::shared_ptr<B> b_ptr_2 = /* do same thing to a_ptr_2 */ nullptr;
    assert(!b_ptr_2);
    assert(b_ptr_1);
    b_ptr_1->bar();
    return 0;
}
c++ inheritance c++20 multiple-inheritance
1个回答
0
投票

您要找的是

std::dynamic_pointer_cast
:

std::shared_ptr<A> a_ptr_1 = std::make_shared<C>();
std::shared_ptr<A> a_ptr_2 = std::make_shared<D>();

auto b_ptr_1 = std::dynamic_pointer_cast<B>(a_ptr_1);
auto b_ptr_2 = std::dynamic_pointer_cast<B>(a_ptr_2);
assert(!b_ptr_2);
assert(b_ptr_1);
b_ptr_1->bar();

在 godbolt.org 上尝试一下

© www.soinside.com 2019 - 2024. All rights reserved.