PDA

View Full Version : سوال: نحوه استفاده صحیح از template ها



hafez1
جمعه 22 اردیبهشت 1391, 21:51 عصر
برنامه ای که کداشو پایین گذاشتم با به کار گیری template نوشته شده.ارور می ده
فک کنم یه جاهایی توی به کار گیری template اشتباه کردم.
برنامه اومده توابع pop و push در stack را به وسیله لینک لیست یک طرفه نوشته.



#include <iostream.h>

template <class Type>

class Stack{

public:
Stack();
~Stack();

void push(Type data);
Type pop();

private:
Type info;
Stack *previous;
};

template <class Type>
Stack<Type> *head;

template <class Type>

int main()
{
head = new Stack<Type>;
Stack stk;
int i, data, numpush, numpop;
cout << "Please enter count push : ";
cin >> numpush;
for(i = 0; i < numpush; i++)
{
cout << "\nPlease enter data (" << i + 1 << ") = ";
cin >> data;
stk.push(data);
}
cout << "\nPlease enter count pop : ";
cin >> numpop;
for(i = 0;i < numpop; i++)
cout << "\npop (" << i + 1 << ") = " << stk.pop();
cout << endl;
return 0;
}

template <class Type>
Stack<Type>::Stack()
{}

template <class Type>
Stack<Type>::~Stack()
{
Stack<Type> *temp = NULL;

while(head->previous != NULL)
{
temp = head->previous;
delete head;head = temp;
}
}

template <class Type> void Stack<Type>::push(Type data)
{
Stack *temp = new Stack<Type>;
temp->info = data;
temp->previous = head;head = temp;
}

template <class Type> Type Stack<Type>::pop(){Type data = 0;

if(head->previous != NULL){Stack<Type> *temp = head;
data = head->info;
head = head->previous;

delete temp;
}

return data;
}

لطفا هرکی می دونه کمکم کنه:بوس:

ASGGSA
شنبه 23 اردیبهشت 1391, 01:29 صبح
سلام.
بلاخره مشکلشو فهمیدم. باید نوع را مشخص کنید (Type).
برنامه بدون خطا:

#include <iostream.h>
template <class Type> class Stack
{
public:
Stack();
~Stack();
void push(Type data);
Type pop();
private:
Type info;
Stack<Type>* previous;
};
Stack<char>* head;
int main()
{
head = new Stack<char>;
Stack<char> stk;
char data;
int i, numpush, numpop;
cout << "Please enter count push : ";
cin >> numpush;
for(i = 0; i < numpush; i++)
{
cout << "\nPlease enter data (" << i + 1 << ") = ";
cin >> data;
stk.push(data);
}
cout << "\nPlease enter count pop : ";
cin >> numpop;
for(i = 0; i < numpop; i++)
cout << "\npop (" << i + 1 << ") = " << stk.pop();
cout << endl;
return 0;
}

template <class Type> Stack<Type>::Stack()
{
}

template <class Type> Stack<Type>::~Stack()
{
while(head->previous != NULL)
{
Stack<Type>* temp = head->previous;
delete head;
head = temp;
}
}
template <class Type> void Stack<Type>::push(Type data)
{
Stack<Type>* temp = new Stack<Type>;
temp->info = data;
temp->previous = head;
head = temp;
}
template <class Type> Type Stack<Type>::pop()
{
Type data = 0;
if(head->previous != NULL)
{
Stack<Type>* temp = head->previous;
head->previous = NULL;
data = head->info;
delete head;
head = temp;
}
return data;
}

hafez1
چهارشنبه 27 اردیبهشت 1391, 23:15 عصر
خیلی ممنووووووووووووووون.