简体   繁体   中英

Template Stack gives error when type is String

I want to create a string stack with template stack implementation but program gives "invalid conversion from int to const char* " error at s_ptr=new T(size); line.

my Stack.h

using namespace std;
template <class T>
class Stack{

    private:
        int size,top;
        T *s_ptr;

    public:
        Stack(int);
        void push(T val);
        T pop();
        bool isfull();
        bool isempty();

};

template <class T>
Stack <T> :: Stack (int maxsize)
{
    size=maxsize;
    top=-1;
    s_ptr=new T(size);
}

template <class T>
void Stack <T> :: push(T value){
    if(!isfull()){
        s_ptr[++top]=value;
    }
    else{
    cout << "Stack is full";
    }
}

template <class T>
T Stack <T> ::pop()
{
    if(!isempty()){
        return s_ptr[top--];
    }
    else{
        cout << "Stack is empty";
    }
}

template <class T>
bool Stack <T>::isfull(){
    return top == size-1 ;
}

template <class T>
bool Stack <T>::isempty(){
    return top ==-1 ;
}

the code in main is

Stack <string> Stack1(50);

How can I solve this problem? Sorry if asked before but I did lots of research. Thanks...

new T(size) makes a single element, initialised with the value size , failing if the type can't be initialised with an int value.

It looks like you want to create an array; that's new T[size] .

Well I guess you want to allocate multiple strings. You are allocating just one string/object.

new string(12)

is calling the std::string constructor, which does not implement string(int)

If you want to allocate multiple strings you have to do:

new string[12]

or new T[size]

Also your class is leaking memory since you never release the allocated memory.

You are incorrectly allocating memory for your array using the instruction:

 s_ptr=new T(size);

Indeed, this line will create a single new object of type T using the constructor T(int size). The error that you receive means that the compiler cannot find any String constructor accepting an int.

What your really need there is allocating memory for size elements of type T. That is:

s_ptr = new T[size];

This will correctly create a pointer to a set of strings.

PS: remember to add a destructor to your Stack implementation that will free the allocated memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM