So above, I declare class in .h file and define some function of those classes in .cpp file.
Now, I wrote a test file to test how it works. Test file test.cpp is like this:
#include <iostream>
#include "my_node.h"
using namespace std;
int main()
{
Stack<float> test_stack;
float a = 2.3;
float b = 3.4;
test_stack.push(a);
test_stack.push(b);
cout << test_stack.pop();
cout << test_stack.pop();
return 0;
}
The command I use is simply:
g++ -g -Wall my_node.cpp test.cpp -o test
The compiling error is like this:
/tmp/ccYaX0on.o: In function `main':
/home/user/cpp/oop_eg/test.cpp:11: undefined reference to `Stack<float>::push(float&)'
/home/user/cpp/oop_eg/test.cpp:12: undefined reference to `Stack<float>::push(float&)'
/home/user/cpp/oop_eg/test.cpp:14: undefined reference to `Stack<float>::pop()'
/home/user/cpp/oop_eg/test.cpp:15: undefined reference to `Stack<float>::pop()'
collect2: ld returned 1 exit status
I feel so strange because I defined all those functions.
Thanks,
Kevin Zhou
المحلول
With templates, you generally have to put the whole thing (declaration and definition) into a header file. That's because the code which uses the template needs to see the definition in order to instantiate it.
Basically, you can probably just cut+paste all the functions from my_node.cpp into my_node.h.