流血开发C++编译器错误 *二叉树

Bloodshed Dev-C++ compiler errors *Binary Trees

本文关键字:错误 二叉树 编译器 C++ 开发      更新时间:2023-10-16

我想对我的代码提供反馈。这是学校的一项作业,我们被要求编写一个交换左右二叉树的函数。教授给我们的课是swapBinaryTrees,其余的留给我们。我收到很多编译器错误,我不确定我的语法哪里出了问题。当我像第 14 行一样编译它时出现错误,预期的初始化声明符"<"令牌引用的行是

void binaryTreeSearch<elemType>::swapSubtreeNodes()

我对第 19 行有相同的错误,即

void binaryTreeSearch<elemType>::swapSubtreeNodes(nodeType<elemType> *p)

对于上述两个,我都有另一个错误,说在"<"标记之前期望";"然后我在我的主函数中得到未声明的标识符

binaryTreeSearch<int> tree;

我还在"int"之前得到预期的主表达式,在"int"之前得到预期的";"然后它告诉我 cout 和 cin 没有声明我不知道这里发生了什么干草包。我将在下面发布我的整个代码,非常感谢任何帮助。

template <class elemType>
struct nodeType
{
       elemType info;
       nodeType<elemType> *lLink;
       nodeType<elemType> *rLink;
};
template <class elemType>
class swapSubtreeNodes
{
};
template <class elemType>
void binaryTreeSearch<elemType>::swapSubtreeNodes()
{
     swapSubtreeNodes(root);
}
template <class elemType>
void binaryTreeSearch<elemType>::swapSubtreeNodes(nodeType<elemType> *p)
{
    root = temp;
    nodeType<elemType> *root;
    nodeType<elemType> *temp;
    if (p == null)
    {
          return;
    }
    else
    {
        swapSubtreeNodes(p->lLink);
        swapSubtreeNodes(p->rLink);                                  
        temp = p->lLink;
        p->lLink = p->rLink;
        p->rLink = temp;
    }
}
int main()
{
    binaryTreeSearch<int> tree;
    int num;
    cout << "This is how we swap'em" << endl;
    cout << "Insert number (press enter after each one entered)." << endl;
    cout << "Enter -999 to complete" << endl;
    tree.insert(0);
    cin >> num;
    while (num != -999)
    {
          tree.insert(num);
          cin >> num;
    }
    cout << "Your swapped binary tree is " << endl;
         tree.swapSubtreeNodes();
         tree.printTree();
         cout << endl;

}

您没有声明binaryTreeSearch类型。因此,您无法为其实现成员函数。您的编译器告诉您,它不知道您的意思

template <class elemType>
void binaryTreeSearch<elemType>::swapSubtreeNodes()

<的位置,因为它不明白你打算binaryTreeSearch成为一个班级。


当你写作时你在做什么:

template <class elemType>
void binaryTreeSearch<elemType>::swapSubtreeNodes()
{
     swapSubtreeNodes(root);
}

是这个;您告诉C++您打算实现一个 int ()() 类型的成员函数swapSubTreeNodes,该函数属于名称binaryTreeSearch的结构化类型(即classstruct),该类型由一个参数模板化。但是,您的编译器(实际上是任何编译器)都会抱怨,因为没有这种类型。如何解决此问题取决于您真正打算做什么。一种选择是声明该类型:

template <class elemType>
class binaryTreeSearch // I really recommend to write types Uppercase!
{
  private:
    nodeType<elemType>* root;
    //                  ^---- that's the variably you are trying to
    //                        access in your original post
  public:
    void swapSubtreeNodes();
    void swapSubtreeNodes(nodeType<elemType>*);
};

这不会修复所有错误,但可能是您打算做的。您可能还希望添加适当的构造函数和析构函数。