[英]When is a `static_cast<Base*>(static_cast<void*>(derived))` from a pointer to a derived class valid?
[英]static_cast an interface to derived class
我試圖static_cast一個接口對象到繼承該接口的派生類的對象。 我收到一個錯誤
'static_cast':無法從'IInherit *'轉換為'cDerived *'
派生的類和接口具有以下格式。
class cDerived: public IInherit
{
Repo* p_Repos;
public:
cDerived(Repo* pRepos)
{
p_Repos = pRepos;
}
Repo* GetRepo()
{
return p_Repos;
}
void doAction(ITok*& pTc)
{
///some logic
}
}
class IInherit
{
public:
virtual ~IInherit() {}
virtual void doAction(ITok*& pTc)=0;
};
我有一個vector<IInherit*>
對象,可通過getInherit()方法在代碼中訪問,使得getInherit()[0]的類型為cDerived *。我正在使用表達式執行靜態強制轉換:
Repo* pRep= static_cast<cDerived*>(getInherit()[0])->GetRepo();
我不確定是否可以將static_cast作為接口對象。 我還有其他方法可以執行此投射嗎?
您可以在示例中使用static_cast
。
但是,您必須同時包含IInherit
和cDerived
定義才能起作用。 編譯器必須看到cDerived
繼承自IInherit
。 否則,它無法確定static_cast
確實有效。
#include <vector>
struct R {};
struct B {};
struct D : public B {
R *getR() { return new R(); }
};
void f()
{
std::vector<B*> v;
v.push_back(new D());
D *d = static_cast<D*>(v[0]);
R *r = d->getR();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.