代码之家  ›  专栏  ›  技术社区  ›  Giogre

C++模板实例化,错误:非类类型“int”的成员

  •  1
  • Giogre  · 技术社区  · 4 年前

    我尝试在C++中实现二叉搜索树。 递归调用函数时遇到问题 Node<T>::append 按照它自己的定义。

    #include <iostream>
    #include <string>
    #include <memory> // std::unique_ptr<>
    
    using namespace::std;
    
    template<class T> class Node {
    public:
        // constructors
        Node() {};
        Node(const T&);
    
        // operations
        void append(const T&);
        void print();
    
    private:
        unique_ptr<T> value, left_child, right_child;
    };
    
    template<class T> class BinaryTree {
    public:
        // constructors
        BinaryTree() {};
        BinaryTree(const T&);
    
        // operations
        void insert(const T&);
        void output();
    
    private:
        Node<T> root;
        int size;
    };
    
    template<class T> Node<T>::Node(const T& in): value(new T (in)), left_child(nullptr), right_child(nullptr) {}
    
    template<class T> void Node<T>::append(const T& in) {
        if (in < *value) {
            if (left_child)
                left_child->append(in);
            else
                left_child(new Node(in));
        } else if (in > *value) {
            if (right_child)
                right_child->append(in);
            else
                right_child(new Node(in));
        }
    }
    
    template<class T> void Node<T>::print() {
        cout << string(6,' ') << "( " << *value << " ) " << endl;
        if (left_child)
            left_child->print();
        if (right_child) {
            cout << string(10,' ');
            right_child->print();
        }
    }
    
    template<class T> BinaryTree<T>::BinaryTree(const T& in): root(in), size(1) {}
    
    template<class T> void BinaryTree<T>::insert(const T& in) {
        root.append(in);
    }
    
    template<class T> void BinaryTree<T>::output() {
        root.print();
    }
    
    int main()
    {
        BinaryTree<int> test(5);
        test.insert(3);
        test.insert(9);
        test.output();
    
        return 0;
    }
    

    g++记录以下错误:

    error: request for member 'append' in 
    '*((Node<int>*)this)->Node<int>::left_child.std::unique_ptr<_Tp, _Dp>::operator-><int, std::default_delete<int> >()', 
    which is of non-class type 'int' left_child->append(in);
    

    left_child->append(in); 不是递归调用,而是对不存在的函数的函子。

    如何解决这个问题? 参见在线编译: https://godbolt.org/z/Pna9e5

    1 回复  |  直到 4 年前
        1
  •  3
  •   3CxEZiVlQ    4 年前

    left_child right_child 不要指向节点。编译器非常清楚地解释了这一点: 属于非类类型“int”left\u child ,左\u子项的类型是int,而不是class。声明

    unique_ptr<T> value, left_child, right_child;
    

    应该是

    unique_ptr<T> value;
    unique_ptr<Node<T>> left_child, right_child;
    

    left_child(new Node(in)); ,left\u child不是函数,语句必须是 left_child.reset(new Node(in));