I am a beginner in c++ so please excuse me if I my mistakes below turn out to be silly. Still, I am stuck with my code and would appreciate any help.
I get the following error when trying to compile through make via g++:
In file included from A.cpp:2:
List.h:20: error: ‘List’ is not a template type
A.cpp: In member function ‘void A::NowyObiekt(int)’:
A.cpp:6: error: ‘list_a’ was not declared in this scope
make: *** [A.o] Error 1
My code is separated into the following tiny files:
- A.h : http://pastebin.com/QQ04xx2j (header)
-
A.cpp : below
#include "A.h" #include "List.h" void A::NewObject(int i) { list_a.Add(i); } int A::Compare(int a, int b) { if ( a>b ) return 1; if ( a<b ) return -1; else return 0; } -
List.h : below (header)
#ifndef LIST_H #define LIST_H template<typename T> class Node { Node() { nxt = pre = 0; } Node(const T& el, Node *n = 0, Node *p = 0 ) { dana = el; nxt = n; pre = p; } T dana; Node *nxt, *pre; }; template<typename T> class List { public: List() { head = tail = 0; } void Add(const T&); protected: Node<T> *head,*tail; }; #endif -
List.cpp : http://pastebin.com/a3HQ9yZ4
-
prog.cpp : below (main)
#include "List.h" #include "A.h" int main() { int i = 5; class List list_a; class A obj; obj.Add(i); } -
and the makefile is : http://pastebin.com/GTR5jW54
As noted, I am still a beginner, so please be understanding. I would be thankful for any help and clear explanations. Thanks in advance.
There are a couple of problems with your code: The first is that you don’t declare any variable named
list_aanywhere. That error should be pretty obvious. The other is that you use theListclass without giving it template parameters.And last a small note about your question: As your files are indeed very small, you could put them in the question and not link to them.
Edit: About the
Listtemplate problem.You already use
Nodeproperly inList, i.e. declare the nodes asNode<T>. When you useListyou simply has to do the same. For example, to declare a list of integers:Also, as you only use public functions in
Listfrom the classA, you don’t need thefrienddeclaration. If you do need to use protected or private members (which IMO is a sign of bad design) you need to make that friend-declaration templated as well:And finally, your code will not compile anyway… The reason being that when you are using a template-class, the whole class has to be fully defined (i.e. complete with its function implementations). You can solve this by putting the functions in the header file. And when defining the functions, you need the template parameter there as well:
Note that I added the template parameter in a couple of places.