这是我的问题有关的类(class)

class Graph {}
class SceneGraph : public Graph {}

class Node {
public:
    virtual Node* getNode(int index) { return mNodeList[index]; }

protected:
    vector<Node*> mNodeList;
    Graph* mGraph;
}

class TransformationNode : public Node {
public:
    TransformationNode* getNode(int index) { return static_cast<TransformationNode*> (mNodelist[index]); }

    void _update() {
        auto beg = mNodeList.begin();
        auto end = mNodeList.end();
        while (begin != end) {
            TransformationNode* node = static_cast<TransformationNode*> (*beg);
            node->_update();
        }
    }

private:
    bool mUpdated;
    SceneGraph* mGraph;
}

首先,我想谈谈我解决的问题。他们可能会帮助他人。您可以确认我是否正确^^
  • 我可以覆盖具有不同返回类型的函数吗?
    Node * getNode(int index)成为TransformationNode * getNode(int index)


  • 我可以覆盖成员吗?



  • 我真的很想解决这个问题

    在TransformationNode类中,我从基类到派生类进行了许多(IMHO)可避免的类型转换。我当然知道mNodeList vector 中的所有元素都是TransformationNodes,但是要处理mNodeList我必须键入强制转换它们。
    继承是正确的,我的意思是TransformationNode是一个Node
    mNodeList包含节点的子节点,并且在派生类中不能具有副本,该派生类中包含节点的转换版本
    最后,如果static_cast的成本更高,我什至可以使用reinterpered_cast。您能告诉我这些手术的费用吗?它们真的是很大的性能问题吗?
    assert(dynamic_cast)...已经采取了某种预防措施。

    简短地,我希望我的编译器知道mGraph实际上是一个SceneGraph *,而mNodeList拥有TransformationNode *,这可以帮助我避免类型转换的丢失。

    谢谢您抽出宝贵的时间

    最佳答案

    1)是正确的,如果返回类型更派生,则实际上可以重写(虚拟!)基函数。

    广告2):实际上,您不能“替代”成员。如果需要更灵活的可重写行为,请重新设计基类。
    static_cast是在编译时解决的静态操作,与reinterpret_cast一样,它没有任何“开销”。

    正如@Seth在评论中建议的那样,可以选择移动容器。问问自己,是否会有抽象的Node,或者每个节点实际上是某种派生的具体类型吗?也许您可以使Node抽象:

    struct Node { Node * getNode(size_t index) const = 0; };
    
    struct TransformNode : Node
    {
        TransformNode * getNode(size_t index) const { return m_nodes[index]; }
    private:
        std::vector<TransformNode *> m_nodes;
    };
    

    将整个接口(interface)放入基类,但仅在每个具体类中实现。

    关于c++ - C++覆盖成员变量(std::vector),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8866384/

    10-09 13:35