Cześć.
Chciałem napisać sobie stos jako template i chyba prawie mi się udało oprócz tego, że gdy na stosie chce umieścić sobie string'a to niestety wywala mi błąd, może mi ktoś podpowiedzieć/powiedzieć dlaczego? Ponadto czy mógłby ktoś mi wyjaśnić różnicę między operatorem << jako funkcja składowa i jako funkcja zaprzyjaźniona?
#include <iostream>
#include<cstdlib>
//#include <string>
#define DEFAULT_INITIAL_SIZE_ 2
using namespace std;
template<class B>
class Stack{
private:
B*data;
long size;
long top;
public:
Stack();
Stack(long size);
~Stack(){
delete[] data;
}
void push(B element){
if(this->top==this->size){
stack_resize();
}
this->data[this->top]=element;
this->top++;
}
friend ostream& operator<<(ostream& os,const Stack & s){
if(s.top==0) return os<<"Stack is empty - nothing to print";
else{
for(int i=0;i<s.top;i++){
os<<s.data[i]<<" ";
}
return os<<"\n";
}
}
int pop(){
if(this->top==0){
cout<<"Can't pop from empty stack"<<endl;
exit(1);
}else{
this->top--;
return *(this->data+this->top);
}
}
bool is_empty(){
if(this->top==0) return true;
else return false;
}
void clear(){
this->top=0;
}
private:
void stack_resize(){
B*temporary_data=new B[2*(this->size)];
for(int i=0;i<(this->size);i++){
temporary_data[i]=(this->data[i]);
}
delete[] this->data;
/
this->data=temporary_data;
this->size=2*(this->size);
}
};
template<class B>
Stack<B>::Stack():size(2), top(0){
/
try{
data=new B[2];
}catch(bad_alloc& ex){
cout<<ex.what()<<endl;
//destruktor ???
}
}
template<class B>
Stack<B>::Stack(long size){
if(size<=0){
data=new B[2];
this->size=2;
this->top=0;
}
else{
try{
this->size=size;
this->top=0;
data=new B[size];
}catch(bad_alloc& ex){
cout<<ex.what()<<endl;
//destruktor ???
}
}
}
Z góry dzięki.