This question already has an answer here:
I just started learning the C++ programming language and am trying to implement a binary search tree data structure.
When I try to compile my files with
g++ -c binary.cpp -o binary.o -std=c++11
g++ -c main.cpp -o main.o -std=c++11
g++ main.o binary.o -std=c++11
then I always get some errors saying there is an "undefined reference" to some member function like
main.o: In function `BSTree<int>::insert(int const&)':
main.cpp:(.text.#some-more-text#.+0x16): undefined reference to
`BSTree<int>::insert(BSTreeNode<int>*, int const&)'
collect2: error: ld returned 1 exit status
The following code snippets are meant to be a minimalistic example:
binary.hpp:
template<typename T>
class BSTreeNode {
public:
T key;
BSTreeNode<T> *left;
BSTreeNode<T> *right;
BSTreeNode(const T& key) : key(key), left(nullptr), right(nullptr) {};
};
template <typename T>
class BSTree {
protected:
BSTreeNode<T> *root;
public:
BSTree() {
root = nullptr;
}
void insert(const T& key) {
root = insert(root, key);
}
protected:
BSTreeNode<T>* insert(BSTreeNode<T>* node, const T& key);
};
binary.cpp
#include "binary.hpp"
template<typename T>
BSTreeNode<T>* BSTree<T>::insert(BSTreeNode<T>* node, const T& key) {
if (not node) {
return new BSTreeNode<T>(key);
}
if (key < node->key) {
node->left = insert(node->left, key);
} else if (key > node->key) {
node->right = insert(node->right, key);
} else {
throw "Key already exists!";
}
return node;
}
main.cpp:
#include "binary.hpp"
#include <math.h>
int main(){
BSTree<int> bt;
for (int i=0; i<10; i++){
bt.insert(pow(-1, i) * i);
}
Even after an exhaustive search I still can't figure out what's wrong with my code.
Aucun commentaire:
Enregistrer un commentaire