心中已經問這些問題,前一段時間: 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