Template Class in C++ to Implement a Stack

649 Views Asked by At

I'm having compilation errors & need help on how to write my methods.

#include <iostream>
#include<string>
#include <vector>
#include<bits/stdc++.h>
using namespace std;

template<class T>
class Stack{
    
    public:
  
    Stack();

    //Requires: nothing.
    //Effects: returns whether a stack is empty or not.
    template <class T> bool empty();
       
    //Method 1.1
    //Requires: passing the constant item by &reference.
    //Effects: adds item to the stack.
    void push(const T& item);

    //Method 1.2
    //Requires: passing the non-constant item by &reference.
    //Effects: adds item to the stack.
    void push(T& item);

    //Method 2
    //Requires: nothing.
    //Effects: returns the item most recently added  to the stack.
    T& top();
       
    //Method 3
    //Requires: nothing.
    //Effects: removes the item most recently added  to the stack.
    void pop();
       
    private:
    
    vector<T> stack; 

};

template <class T> Stack<T>::Stack() {  }
 
template <class T> Stack<T>::empty(){ return stack.empty()}


int main(){

}

These are the compilation errors I'm getting:

prototype for 'int Stack::empty()' does not match any in class 'Stack' Stack::empty(){ }

stack.v.cpp:16:29: error: candidate is: template template bool Stack::empty() template bool empty();

1

There are 1 best solutions below

0
WhozCraig On
  • The template<T> specifier on empty() is not needed. The template parameter T is already provided from the class template parameter list.
  • There are obvious syntax errors, such as not specifying the return type for empty in the out-of-class implementation, and missing a semi-colon in that same function.
#include <iostream>
#include <vector>

template<class T>
class Stack
{    
public:  
    Stack();

    //Requires: nothing.
    //Effects: returns whether a stack is empty or not.
    bool empty();

    //Method 1.1
    //Requires: passing the constant item by &reference.
    //Effects: adds item to the stack.
    void push(const T& item);

    //Method 1.2
    //Requires: passing the non-constant item by &reference.
    //Effects: adds item to the stack.
    void push(T& item);

    //Method 2
    //Requires: nothing.
    //Effects: returns the item most recently added  to the stack.
    T& top();
       
    //Method 3
    //Requires: nothing.
    //Effects: removes the item most recently added  to the stack.
    void pop();
       
private:    
    std::vector<T> stack; 
};

template <class T> Stack<T>::Stack() 
{    
}
 
template <class T> bool Stack<T>::empty() 
{ 
    return stack.empty();
}

int main()
{
    Stack<int> st;
}

There are other things that can/should be done. For example, empty() is a non-mutating function (i.e. it isn't intended to modify your object) and as such should be const. But that is not related to your immediate problem(s).