我试图执行以下强制转换,但在QT文档中或在线上都找不到一种方法来使这种动态的强制转换工作变得令人困惑:
class Entity : public QSharedData
{
public:
typedef QExplicitlySharedDataPointer<Entity> Pointer;
typedef QExplicitlySharedDataPointer<const Entity> ConstPointer;
...
}
class EntityExtended : public Entity
{
public:
typedef QExplicitlySharedDataPointer<EntityExtended> Pointer;
typedef QExplicitlySharedDataPointer<const EntityExtended> ConstPointer;
...
}
bool SomeClass::createEntity(const Entity::ConstPointer entity)
{
auto extendedEntity = dynamic_cast<const EntityExtended::ConstPointer>(entity);
}上面的内容会产生错误:
error C2680: 'const EntityExtended::ConstPointer': invalid target type for dynamic_cast
note: target type must be a pointer or reference to a defined class我遗漏了什么?
发布于 2022-08-10 16:00:34
问题是您只能在原始指针上使用dynamic_cast。尽管QExplicitlySharedDataPointer是一个像指针一样使用的类,但它不是原始指针,因此不能在其上使用dynamic_cast。
解决方案是使用QExplicitlySharedDataPointer的data()或constData()方法获取原始指针,然后在原始指针上使用dynamic_cast,然后通过将原始指针传递给QExplicitlySharedDataPointer constructor将其转换回QExplicitlySharedDataPointer。
bool SomeClass::createEntity(const Entity::ConstPointer entity)
{
//Create a raw pointer to use with dynamic_cast
const EntityExtended *rawPointer = dynamic_cast<const EntityExtended*>(entity.constData());
//Convert the raw pointer back to a QExplicitlySharedDataPointer
EntityExtended::ConstPointer extendedEntity = EntityExtended::ConstPointer(rawPointer);
if(extendedEntity == nullptr){
//*entity is not an instance of ExtendedEntity
}
else{
//*entity is an instance of ExtendedEntity
}
}https://stackoverflow.com/questions/69034335
复制相似问题