I have no idea how can I pass the class I created (Trivial class) to the template class (Stack class).
Below passing pre-defined type such as int, double, char works fine.
some codes i wrote in main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Stack <int> int_stk; //this works fine
Stack <char> char_stk; //this works fine
int_stk.push(1);
int_stk.push(2);
int_stk.push(3);
int_stk.size(); // outputs 3
int_stk.pop(); // outputs 3
int_stk.pop(); // outputs 2
int_stk.pop(); // outputs 1
int_stk.pop(); // outputs "The stack is empty."
int_stk.size(); // outputs 0
//My problem is below
Stack <Trivial> trivial_stk; //gives error
trivial_stk.push("Hello");
trivial_stk.push("Hi");
trivial_stk.push("GoodBye");
Stack class header file (I didnt include the cpp file)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
template< class T >
class Stack
{
public:
Stack( int = 10 ); // default constructor (stack maxSize 10)
~Stack();
void push( const T& );
void pop();
bool isEmpty() const;
bool isFull() const;
void size() const;
void peek(constint&) const;
private:
int maxSize; // number of elements in the stack
int top; // location of the top element
T *stackPtr; // pointer to the stack
};
error C2512: 'Trivial' : no appropriate default constructor available ...
while compiling class template member function 'Stack<T>::Stack(int)'
1> with
1> [
1> T=Trivial
1> ]
1> c:\users\dexter\desktop\c++2\as4\driver.cpp(93) : see reference to function template instantiation 'Stack<T>::Stack(int)' being compiled
1> with
1> [
1> T=Trivial
1> ]
1> c:\users\dexter\desktop\c++2\as4\driver.cpp(93) : see reference to class template instantiation 'Stack<T>' being compiled
1> with
1> [
1> T=Trivial
1> ]
............
error C2679: binary '<<' : no operator found which takes a right-hand operand of type
'Trivial' (or there is no acceptable conversion)
could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
Compiliation was successful. However, after console was up,
it gave me a message like : Debug Assertion Failed! ... Line:1154 .... Expression: invalid null pointer...
// constructor
template< class T >
Stack< T >::Stack( int s = 10) {
maxSize = s;
top = -1; // stack initially empty
stackPtr = new T[ maxSize ]; // allocate memory for elements
}
// destructor
template< class T >
Stack< T >::~Stack() {
delete [] stackPtr;
}
// push element onto stack;
template< class T >
void Stack< T >::push( const T &value ) {
if ( !isFull() )
stackPtr[ ++top ] = value;
else
cout <<"Stack is full" << endl;
}
// pop element off stack;
template< class T >
void Stack< T >::pop() {
if ( !isEmpty() )
cout<<stackPtr[ top--] << endl; // remove item from Stack
else
cout<<"Stack is empty" << endl;
}
// check if stack is empty
template< class T >
bool Stack< T >::isEmpty() const {
return top == -1;
}