Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 类和嵌套类中的继承_C++_Templates_Inheritance - Fatal编程技术网

C++ 类和嵌套类中的继承

C++ 类和嵌套类中的继承,c++,templates,inheritance,C++,Templates,Inheritance,我有一个表示树的基类 class BaseTree { protected: class Node { public: Node* left() { return children[0]; } Node* right() { return children[1]; } protected: std::vector<Node*> children; };

我有一个表示树的基类

class BaseTree
{
protected:
    class Node
    {
    public:
        Node* left()
        { return children[0]; }

        Node* right()
        { return children[1]; }

    protected:
        std::vector<Node*> children;
    };

    Node* root;

public:
    Node* get_root()
    { return root; }
};
问题在于,在
DerivedTree
DerivedTree::Node
中,继承成员函数和继承变量
root
的返回类型将是
BaseTree::Node*


是否有办法在
DerivedTree
DerivedTree::Node
中生成返回类型,而不是在
BaseTree::Node
中生成返回类型?

这是否意味着要以多态方式使用?如果不是,那么您所拥有的应该可以工作。@imreal我已经添加了几行代码,显示我正在尝试做什么,以及我遇到了什么错误。如果您将
get\u root
函数设置为虚拟,您可以覆盖它并使返回类型变为协变量。
third\u node
方法意味着派生类型。如果你知道它有那种类型,你也可以投下它<代码>静态_cast(树->获取_根())->第三个_节点()@Gaith-您必须强制转换,但您可以在重写函数中执行,就像我建议的那样。
class DerivedTree : public BaseTree
{
protected:
    class Node : public BaseTree::Node
    {
    public:
        Node* third_node()
        { return (Node*)children[2]; }
    };
};

int main()
{
    DerivedTree* tree = new DerivedTree();
    tree->get_root()->third_node(); // ERROR: ‘class BaseTree::Node’ has no member named ‘third_node’
}