| re: How do I declare a template class variable and make an instance seperately?
Irish wrote:[color=blue]
> Hello all :)
> Hopefully someone can shed some light on this problem I'm having. I'm
> trying to declare a variable to a type of class I've defined (which is
> a minHeap), but actually instantiate it later when I get a command from
> the user.[/color]
Don't declare it until you're ready to use it.
[color=blue]
> This is my class and if you look down a lil you can see what
> I'm trying to do in my main(). I want to ask for the size from the
> user, but when I try to I can't get my code to compile. Here is the
> class definition and the constructor. This is the error I'm getting.
>
> /Users/ci/minheap/minheap.h:42: error: prototype for 'HEAP<T>::HEAP()'
> does not match any in class 'HEAP<T>'[/color]
Because you haven't defined a default constructor ... but you actually
don't need it, if you just defer declaring the variable until you need
it.
[color=blue]
> #-------------------------------------------------------------
> #include <cstdlib>
> #include <iostream>
> using namespace std;
>
> struct ELEMENT{int key;};
>
> template<class T>
> class HEAP {
> public:
> HEAP(int n);
> ~HEAP(){ delete [] heap;}
> T Min(){if (CurrentSize == 0)
> throw OutOfBounds();
> return heap[0];}
>
> HEAP<T>& Insert(int k);
> int DeleteMin();
>
> void printHeap() const;
>
> private:
> int CurrentSize, Capacity;
> T *heap; // element array
> };
>
> template<class T>
> HEAP<T>::HEAP(int n){ //constructor.
> Capacity = n;
> cout << "Heap's Capacity is: " << Capacity << endl;
> heap = new ELEMENT[Capacity];
> CurrentSize = 0;
> }
>
> int main(void){
>
> HEAP<ELEMENT> A(10); //THIS WORKS FINE[/color]
Delete the following line entirely.
[color=blue]
> HEAP<ELEMENT> B; // I CAN'T DO THIS THOUGH...why?? how can
> I??
>
> int size;
>
> cout << "Give the desired size of this heap: " << endl;
> cin >> size;
> B(size); // I WANT TO INSTANTIATE B DOWN HERE[/color]
For the preceding line, substitute:
HEAP<ELEMENT>B(size);
[color=blue]
>
> }[/color]
Best regards,
Tom |