![](/img/trans.png)
[英]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.