2个类之间的继承关系[关闭]

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

假设我们有两个类--Y和X.

现在,假设我们有以下代码段:

Y y;
X &x = y;

通过这个标题,我们怎么知道这些类之间存在继承关系?

我们怎么知道Y类继承了X类呢?

c++ inheritance
1个回答
0
投票

检查类之间“关系”的最常用方法之一是使用dynamic_cast。如果转换失败,它将返回nullptr,因此最好使用指针而不是引用(要使用它们,您必须检查异常)。

这是一个例子:

#include <iostream>
#include <memory>

class X
{
public:
    virtual ~X() = default;
    X() = default;
};

class Y : public X
{
public:
    virtual ~Y() = default;
    Y() = default;
};

class Z
{
public:
    virtual ~Z() = default;
    Z() = default;
};

template<class Derived, class Base>
bool isType(Derived *checkedType)
{
    return checkedType != nullptr && dynamic_cast<Base *>(checkedType) != nullptr;
}

int main() {
    std::shared_ptr<Y> y = std::make_shared<Y>();

    if(isType<Y,X>(y.get()))
        std::cout<<"There is relation between 2 classes!\n";
    if(!isType<Y,Z>(y.get()))
        std::cout<<"There is no relation between 2 classes!";
}
© www.soinside.com 2019 - 2024. All rights reserved.