Nicholas Tree Nicholas Tree - 1 month ago 14
C++ Question

Binary Search Tree Implementation. Problems With Compilation

Basically, I'm getting problems in both the header file and the cpp file with the search function. It just says "Member declaration not found" and "prototype for 'node *BTree::search(int) does not match any in class BTree". I only listed the search functions in the cpp file to make it easier, because my insert and destroy_tree functions both work fine.

Header file:

#ifndef BTREE_H_
#define BTREE_H_

class BTree {


public:
struct node{

int key_value;
node *left;
node *right;
};

BTree();
virtual ~BTree();

void insert(int key);
node* search(int key);
void destroy_tree();
node *root;


private:

void insert(int key, node *leaf);
node* search(int key, node *leaf);
void destroy_tree(node *leaf);



};

#endif /* BTREE_H_ */


Implementation:

#include "BTree.h"
#include <iostream>
using namespace std;
struct node{

int key_value;
node *left;
node *right;
};

BTree::BTree() {

root = NULL;
}

BTree::~BTree() {

destroy_tree();
}

node BTree::*search(int key, node *leaf){

if(leaf != NULL){

if(key == leaf->key_value){

return leaf;
}
if(key < leaf->key_value){

return search(key, leaf->left);
}

else{

return search(key, leaf->right);
}
}
else return NULL;
}


node *BTree::search(int key){

return search(key, root);
}

Answer

You have two struct node structs, one declared globally (in your .cpp file) and one declared within the BTree class. These are two different structures, one named ::node (global), the other BTree::node. In your header file search refers to the one defined within the class, while the function declaration in the .cpp file refers to the global one.

Remove the global struct, and declare the search function using BTree::node *BTree::search instead.