将接口静态转换为派生类

static_cast an interface to derived class

本文关键字:派生 转换 接口 静态      更新时间:2023-10-16

我试图将接口对象静态转换为继承该接口的派生类的对象。我得到一个错误

'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;
};

我有一个可以在代码中通过getInherit()方法访问的vector<IInherit*>对象,使getInherit()[0]的类型为cDerived*我正在使用表达式执行静态强制转换:

Repo* pRep= static_cast<cDerived*>(getInherit()[0])->GetRepo();

我不确定是否可以将static_cast作为接口对象。还有别的方法可以让我表演这个角色吗?

您可以在示例中使用static_cast

但是必须包含 IInheritcDerived的两个定义才能工作。编译器必须看到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();
}

如果vector的成员总是派生类型,也可以考虑使用vector<cDerived*>。这将完全避免强制转换:

std::vector<D*> v;
v.push_back(new D());
R *r = v[0]->getR();