将接口静态转换为派生类
static_cast an interface to derived class
我试图将接口对象静态转换为继承该接口的派生类的对象。我得到一个错误
'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
。
但是必须包含 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();
}
如果vector的成员总是派生类型,也可以考虑使用vector<cDerived*>
。这将完全避免强制转换:
std::vector<D*> v;
v.push_back(new D());
R *r = v[0]->getR();
相关文章:
- 存储模板类型以强制转换回派生<T>
- 在 C++ 中将对象转换为派生类型
- 从基类实例调用派生类方法而不进行强制转换
- 从基指针到派生的强制转换问题
- C++将派生类转换为基类时'object slicing'期间发生的情况
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- C ++基础私有方法在将自身转换为派生类后可以访问吗?
- 调用不在基类中的派生类函数而不进行动态强制转换,以最大程度地提高性能
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- 为什么从基转换为派生提供此功能?
- 将基本实例指针强制转换为派生实例指针是否合法?(实例不是派生实例)
- 从从该抽象类派生的 Python 对象强制转换C++抽象类C++
- 基类到派生类的强制转换向量
- 有没有办法复制派生类指针的向量而不将其强制转换为基类?
- 为什么此代码不将基类强制转换为 c++ 中的派生类?
- 如何在运行时将指向派生类的 void* 正确转换为指向基类的 void*
- 从基类的共享指针向下转换到派生类的引用
- 为了访问方法,从基类动态转换为派生类
- 如何将矢量<派生*>转换为矢量<Base*时避免复制>