Dec 26, 2013 at 8:12pm UTC
Hello,
I'm trying to write my first class on C++.
So I have the following 3 files:
leftist_heap.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#ifndef LEFTIST_HEAP_H_
#define LEFTIST_HEAP_H_
template <typename T>
class Heap {
private :
T *object;
Heap *left, *right;
int key;
public :
Heap(T *object, int key);
void insert(T* object, int key);
T* min(void );
// Gets and Sets
void setObject(T*);
T* getObject();
void setKey(int );
int getKey();
};
#endif
leftist_heap.cc:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include "leftist_heap.h"
#include <cstdlib>
template <typename T>
Heap<T>::Heap(T* object, int key) {
this ->object = object;
this ->key = key;
this ->left = this ->right = NULL;
}
template <typename T>
T* Heap<T>::min() {
return this ->getT();
}
template <typename T>
int Heap<T>::getKey() {
return this ->key;
}
template <typename T>
void Heap<T>::setKey(int key) {
this ->key = key;
}
template <typename T>
void Heap<T>::setObject(T* object) {
this ->object = object;
}
template <typename T>
T* Heap<T>::getObject() {
return this ->object;
}
and main.cc:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include "leftist_heap.h"
int main() {
int *i = new int (1);
Heap<int > *heap;
heap = new Heap<int >(i,1);
return 0;
}
But when I compile it with this commands:
1 2 3
g++ -c main.cc -I ./
g++ -c leftist_heap.cc -I ./
g++ -o main main.o leftist_heap.o
I get this error:
1 2 3 4 5 6
Undefined symbols for architecture x86_64:
"Heap<int>::Heap(int*, int)" , referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [main] Error 1
I believe my problem is in main.cc, but I can't understand why.
Solution:
I found my answer here:
http://www.cplusplus.com/forum/articles/14272/
Last edited on Dec 27, 2013 at 12:30am UTC
Dec 26, 2013 at 8:45pm UTC
You cannot do that, you have to declare templates fully inline.
Wrong:
1 2 3 4 5
template <typename T>
struct Class
{
Class();
};
Right:
1 2 3 4 5 6 7 8
template <typename T>
struct Class
{
Class()
{
//...
}
};
With templates you should never have a .cpp or .cc file, only a .hpp or .hh file.
Last edited on Dec 26, 2013 at 8:45pm UTC