Fehler finden in Template?
-
Was ist hier falsch? Wenn ich eine normale Klasse mit Double anstatt T schreibe, bekomme ich kein Fehler und als Template:
Template_example error LNK2019: unresolved external symbol "public: bool __thiscall Stack<double>::pop(double &)" (?pop@?$Stack@N@@QAE_NAAN@Z) referenced in function _mainmain.cpp
#include<iostream> using std::cout; using std::cin; using std::endl; #include "tstack.h" int main() { Stack<double> doubleStack(5); double f=1.1; cout<<"Pushing elements onto doubleStack\n"; while(doubleStack.push(f)){ cout<<f<<' '; f +=1.1; } cout<<"\nStack is full. Cannot push"<<f <<"\n\nPoping"; while(doubleStack.pop(f)) cout<<f<<' '; cout<<"\nStack is empty. Cannot pop\n"; return 0; }tstack.h
#ifndef TSTACK_H #define TSTACK_H template<class T> class Stack{ public: Stack(int s=10); ~Stack(){delete [] stackPtr; stackPtr=NULL;} bool push(const T&); bool pop(T &); private: int size; int top; T *stackPtr; bool isEmpty() const {return top==-1;} bool isFull() const {return top==size-1;} }; #endiftsctack.cpp
#include "tstack.h" template<class T> Stack<T>::Stack(int s) //Stack::Stack(int s) { size=s>0? s : 10; top=-1; stackPtr=new T[size]; } template<class T> bool Stack<T>::push(const T &pushValue) //bool Stack::push(const double &pushValue) { if(!isFull()){ stackPtr[++top]=pushValue; return true; } return false; } template<class T> bool Stack<T>::pop(T &popvalue) { if(!isEmpty()){ popValue=stackPtr[top--]; return true; } return false; }
-
Bei Templates solltest du die Funktionen in der Headerdatei definieren.
-
nicht solltest, musst. und das ist auch die lösung für das problem.
-
-
Wenn das ganze Template in tstack.h deklariert und implementiert wird, habe ich kein Fehler....
Warum ?
Ich programmiere mit Visual Studio.NET
-
carmen schrieb:
Wenn das ganze Template in tstack.h deklariert und implementiert wird, habe ich kein Fehler....
Warum ?
Ich programmiere mit Visual Studio.NETweil du eben damit das problem gelöst hast!
templates "kannst" du nicht in mehrere dateien aufteilen!
-
HERZLICHEN DANK!