C ++:从“ Basenode*”到“匹配*”的无效转换
-
19-08-2019 - |
题
我程序中的所有对象都从容器类继承。容器类有一个 virtual BaseNode* getParent() const;
方法和 virtual void setParent(BaseNode *p);
方法。
我有一个 Set
类(在网球比赛中设置,而不是数据结构),其中 Match
上课时是父母(通过 setParent()
) 但是由于 Set
继承 Container
, ,该程序从自上而下创建树结构, Set
班级是孩子,它不需要有方法来跟踪和维护有关其父母的信息 Container
提供。
错误 C++: invalid conversion from ‘BaseNode*’ to ‘Match*’
当我尝试编译程序时,显示在下面的方法中。 ((Player* getPlayer1() const;
仅存在于 Match
班级)
Player* Set::getPlayer1() const{
return getParent()->getPlayer1();
}
这是我的继承结构。 (注意 TreeNode
是模板)
Match -> TreeNode<Set> -> BaseNode -> Container
我不明白为什么我会遇到对话错误。我尝试阅读我的教科书,但这是一个相当糟糕的参考。 Google只是提供了太多无关的信息。
编辑
Player* Set::getPlayer1() const{
return dynamic_cast<Match>(getParent())->getPlayer1();
}
原因
error: cannot dynamic_cast ‘#‘obj_type_ref’ not supported by dump_expr#<expression error>((&((const Set*)this)->Set::<anonymous>))’ (of type ‘class BaseNode*’) to type ‘class Match’ (target is not pointer or reference)
编辑2
我只是意识到我需要 dynamic_cast<Match*>
有效。
解决方案
问题是 getParent()
返回a BaseNode*
, ,这可能是任何类型的指针 BaseNode
- 它可能指出一个无关的类,也来自 BaseNode
. 。如果您100%确定父母必须是类型 Match
, ,你应该把父母扔到 Match*
首先,然后您可以致电 getPlayer()
这样:
Player* Set::getPlayer1() const{
return dynamic_cast<Match*>(getParent())->getPlayer1();
}
如果父母不需要 Match
, , 然后 dynamic_cast
可能返回null,因此请务必检查一下。
其他提示
我认为您确实需要重新组织层次结构和方法名称...这与您的问题无关,但是总的来说,很难理解为什么从匹配中设置继承。 (比赛没有设置吗?)
游戏是由积分组成的,场景由游戏组成,比赛由套装组成……球员赢得了积分。
您可能应该更紧密地与现实世界结构。
只是我的$ .02
编辑
我可能有一个匹配对象,该对象包含集合的映射(IE集合一个,三个三等),而方法player(int)而不是player1()和player2()。同样,似乎没有必要在设定类中使用播放器的方法。一组将指向比赛的比赛。