【发布时间】:2012-05-01 16:31:18
【问题描述】:
我前段时间问过这些问题: Multiple inheritance casting from base class to different derived class
但我仍然不确定我是否理解答案。 问题是:下面的代码有效吗?
#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;
}
代码按我的意愿工作。但据我了解,根据前面的问题,它不应该。所以我不确定这样的代码是否有效。谢谢!
【问题讨论】:
-
您上一个问题的答案中的 cmets 确实解释了
dynamic_cast将适用于您的情况。
标签: c++ casting multiple-inheritance