心中已经问这些问题,前一段时间: Multiple inheritance casting from base class to different derived classC++运行时检查,如果对象实现了接口
但我还是不知道我理解的答案。 现在的问题是:下面的代码是否有效?
#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;
}
该代码正常工作。但据我了解,根据上一个问题,它不应该。所以我不确定这样的代码是否有效。谢谢!
您对上一个问题的回答中的注释确实解释了'dynamic_cast'将适用于您的案例。 – Chad