我试图将接口对象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;
};
Run Code Online (Sandbox Code Playgroud)
我vector<IInherit*>通过getInherit()方法在代码中可以访问一个对象,这样getInherit()[0]的类型是cDerived*我正在使用表达式执行静态转换:
Repo* pRep= static_cast<cDerived*>(getInherit()[0])->GetRepo();
Run Code Online (Sandbox Code Playgroud)
我不确定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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7968 次 |
| 最近记录: |