gpt4 book ai didi

c++ - 模板类中的c++运算符重载Im正在尝试构建重载<<以打印树

转载 作者:行者123 更新时间:2023-12-02 11:13:16 25 4
gpt4 key购买 nike

#pragma once

#include <iostream>
#include <cstdlib>
using namespace std;


template<class T>
class BinarySearchTree {
public:
BinarySearchTree() {
root = NULL;
};

class Node{
public:
Node* left;
Node* right;
Node* parent;
T data;
};
Node* root;
int Size(Node*);
void insert(T);
bool Exsist(T);
void PrintTree(Node*);
T Size();
bool isEmpty() const {
return root==NULL;
}
template < class T>
friend ostream& operator<< (ostream& os, const Node& a);

};


template <class T>
void BinarySearchTree<T>::insert(T d)
{
Node* t = new Node;
Node* parent;
t->data = d;
t->right = NULL;
t->left = NULL;
parent = NULL;
if(isEmpty())
root = t;
else
{
Node* curr;
curr = root;
while(curr)
{
parent = curr;
if(t->data > curr->data)
curr = curr->right;
else
curr = curr->left;
}

if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}


template <class T>
bool BinarySearchTree<T>::Exsist(T d)
{
bool found = NULL;
Node* curr = root;
while(curr != NULL && !found)
{
if( d == curr->data )
{
cout << "The number is in the tree" << endl;
found = true;
}
else if( d > curr->data)
curr = curr->right;
else if(d < curr->data)
curr = curr->left;
}
if( !found )
cout << "The number not found" << endl;
return found;
}


template <class T>
int BinarySearchTree<T>::Size(Node* a)
{
if (a == NULL) return 0;
else
return(1 + Size(a->left) + Size(a->right));

}

template < class T>
ostream& operator<< (ostream& os, const Node& a) //line 102
{
PrintTree(a);
os << endl;
return os;
}

template <class T>
void BinarySearchTree<T>::PrintTree(Node* tree)
{
if (tree!=NULL) {
cout << tree->data << ", " ;
PrintTree(tree->right);
PrintTree(tree->left);

}
}


-编辑-
我更改了它,现在仅在实现上有错误

错误1错误C4430:缺少类型说明符-假定为int。注意:C++不支持default-int 102
错误2错误C2143:语法错误:在'&'102之前缺少','

最佳答案

声明上存在语法错误,实现由重载运算符代替

template < class T>
ostream& operator<< (ostream& os, const Node<T>& a);

在声明和执行中。

关于c++ - 模板类中的c++运算符重载Im正在尝试构建重载<<以打印树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41668162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com