返回指向类定义的结构体的指针,多个作用域操作符

Returning a pointer to a struct defined of a class, multiple scope operators

本文关键字:操作符 作用域 指针 结构体 定义 返回      更新时间:2023-10-16

我的基本二叉树头文件包括以下内容:

template<typename T>
    class Btree{
        // OVERVIEW:    a binary tree with flexible structure that is not sorted
    private:
        struct node {           //a container object 
            node *left;     //left and right tree
            node *right;
            T *o;       // pointer to  object of node
        };
    public:
        node *root; //pointer to the root of the tree (NULL if empty)
        node* insert (node *parent, T *child, int child);
        //MODIFIES: this
        //EFFECTS:  creates a node that stores a pointer to the new child 
        //      and returns the pointer to the node of the new child    
        //      the integer child is either 0, for left child,
        //      or anything else for right child    
            //  void printTree (node * root);
        //EFFECTS:  takes the root of a tree and prints the tree's 
        //      coordinates  
        Btree(){};  //ctor
        Btree(){}   //dtor

    };
    #include "btree.cpp"

我的.cpp看起来是这样的,注意它包含在我的头文件的底部,以避免模板编译器错误:

   template <typename T>
    Btree<T> :: node * Btree<T>::insert (node *parent, T *child, int child)
    {
        node *np = new node;
        np-> o = child; 
        np->left = NULL;
        np->right  = NULL;
        if (child == 0)
            parent->left = np;
        else
            parent->right = np;
        return np;
    } 
但是,我得到以下编译错误:

btree.cpp:3: error: expected constructor, destructor, or type conversion before ‘*’ token

我正在编译g++,版本4.1.2。

有人能帮忙吗?

首先,你的析构函数前面应该有一个~,所以修改

Btree();    //ctor
Btree(){}   //dtor

Btree();    //ctor
~Btree(){}   //dtor

第二,在insert的返回类型之前需要typename,因为它是一个依赖类型:

   template <typename T>
   typename Btree<T>::node* Btree<T>::insert(node *parent, T *child, int child)
// ^^^^^^^^ <- needed
   {
    node *np = new node;
    np-> o = child; 
    np->left = NULL;
    np->right  = NULL;
    if (child == 0)
        parent->left = np;
    else
        parent->right = np;
    return np;
   } 

您还需要重命名您的一个参数,您有两个名为child