章末問題やっていてふっと疑問に思ったことがあります。
プログラム:抽象クラスlistをオーバーライドしてstack(スタック),queue(キュー),sorted(整列済みリスト)を作ること。
#include<iostream>
#include "../CPP-1/myheader.h"
#include<iomanip>
using namespace std;
class list{
public:
list *head,*tail;
list *next;
int num;
list(){head=tail=next=NULL;}
virtual void store(int) = 0;
virtual int retrieve() = 0;
};
class stack : public list{
public:
void store(int);
int retrieve();
};
void stack::store(int key){
list *p = new stack;
if(!p) return ;
p->num = key;
if(head) p->next = head;
head = p;
}
int stack::retrieve(){
int num;
list *p=head;
if(!p) return 0;
num=p->num;
head = p->next;
delete p;
return num;
}
int main(){
int num;
list *p;
stack a; //なぜstack a(); にするとうまくいかないのかどうも説明つきません
p = &a;
p->store(12); p->store(2); p->store(322);
while(num=p->retrieve()) cout << num << endl;
return 0;
}