c++ 在运行时检查对象是否实现了接口

And*_*rew 4 c++ casting multiple-inheritance

我前段时间问过这些问题: 从基类到不同派生类的多重继承转换

但我仍然不确定我是否理解答案。问题是:下面的代码有效吗?

#include <iostream>

using namespace std;

struct Base
{
    virtual void printName() 
    {
        cout << "Base" << endl;
    }
};

struct Interface
{
    virtual void foo()
    {
        cout << "Foo function" << endl;
    }
};

struct Derived : public Base, public Interface
{
    virtual void printName()
    {
        cout << "Derived" << endl;
    }
};

int main(int argc, const char * argv[])
{
    Base *b = new Derived();
    Interface *i = dynamic_cast<Interface*>(b);
    i->foo();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码按我的意愿工作。但据我所知,根据上一个问题,它不应该。所以我不确定这样的代码是否有效。谢谢!

Alo*_*ave 5

它是有效的代码。

为什么?
因为dynamic_cast告诉您所指向的对象是否实际上是您要转换到的类型。
在这种情况下,所指向的实际对象是该类型的,Derived并且该类型的每个对象Derived也是该类型的Interface(因为Derived继承自Interface),因此dynamic_cast是有效的并且可以工作。

  • @Andrew:`dynamic_cast` 仅适用于类中至少有一个 `virtual` 方法(又名多态类)。参见 [this](http://stackoverflow.com/questions/4227328/faq-why-does-dynamic -cast-only-work-if-a-class-has-at-least-1-virtual-method)。您之前的示例没有任何“virtual”方法,因此无法使用“dynamic_cast”。 (2认同)