Using Classes

W

Will Oram

Hi -- me again. This time, I swear I have an on-topic post. :)
Again I apologise for any etiquette violations -- I don't use Usenet
frequently, so I'm not terribly aware of the minute rules. Bear with me
if I goof again.

Anyway, I have a program with two files, a header and a cpp main. The
header contains a class that handles a stack of ints (don't mind that I
simplified it down to a few lines for ease of reading). This code builds
fine.

// MAIN FILE

#include <iostream>
#include "stack2.h"

using namespace std;

int main () {
stack myStack;
return 0;
}

// -----------
// HEADER FILE

// FILE: stack2.h

#ifndef MAIN_SAVITCH_STACK2_H
#define MAIN_SAVITCH_STACK2_H

#include <cstdlib> // Provides NULL and size_t
#include "node2.h"

class stack {
public:
stack( ) { top_ptr = NULL; }
void push(const int& entry);
private:
int *top_ptr; // Points to top of stack
} };

#endif

// END CODE

However, I want to turn the above class into a template class. Tacking
on template <class Item> to the top of the class and changing int *top_
ptr to Item *top_ptr seems like it would be all that's necessary, but it
doesn't compile when I do this. The compiler complains that a) parse
error before ';', b) 'stack' is undeclared.

What is wrong? Thanks.
 
W

Will Oram

I realised I forgot a few things:
* I didn't just simplify the code for reading here...I commented out all
the excess stuff just to accomplish this basic task.
* I realise push()'s parameter would have to be converted to the Item
template as well as the other two changes I thought of. Still, because I
never use push(), it shouldn't impact the compiling.

Thanks.
 
R

Rob Williscroft

Will Oram wrote in
However, I want to turn the above class into a template class. Tacking
on template <class Item> to the top of the class and changing int
*top_ ptr to Item *top_ptr seems like it would be all that's
necessary, but it doesn't compile when I do this. The compiler
complains that a) parse error before ';', b) 'stack' is undeclared.

What is wrong? Thanks.

Note the "stack< int >" in main(), also the argument type of push().

template < typename Item >
class stack
{
public:
stack( ) { top_ptr = NULL; }
void push(const Item& entry);
private:
Item *top_ptr; // Points to top of stack
};


int main()
{
stack< int > myStack;
}

HTH.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,372
Latest member
LucretiaFo

Latest Threads

Top