ListAsSLLクラス(単独リンクリスト)を装飾してListAsDLLクラス(二重リンクリスト)を作成しました。今度はIteratorクラスを組み込み、ListAsDLLクラスを循環させたいと思います。次のように私のコードは次のとおりです。デコレータとイテレータのデザインパターンを使用してフレンドクラスを宣言する方法
#include <iostream>
using namespace std;
class ListAsSLL
{
protected:
struct node{
int i;
struct node* next;
};
node* head;
node* tail;
int listSize;
public:
ListAsSLL()
{
head = 0;
tail = 0;
listSize = 0;
}
virtual void addToBeginning(int i)
{
node * temp = new node;
temp->i = i;
if(head==0){
temp->next = 0;
tail = temp;
}else if(head == tail) {
temp->next = tail;
}
else{
temp->next = head;
}
head = temp;
listSize++;
}
virtual void print()
{
node* temp = head;
for (int i = 0; i < listSize; ++i) {
cout<<temp->i<<" "<<endl;
temp = temp->next;
}
}
};
class Decorator : public ListAsSLL
{
private:
ListAsSLL* list;
public:
Decorator(ListAsSLL* l)
{
list = l;
}
virtual void addToBeginning(int i)
{
list->addToBeginning(i);
}
virtual void print()
{
list->print();
}
};
class PreviousDecorator : public Decorator
{
protected:
struct dnode : public node
{
node* prev;
};
dnode* head;
dnode* tail;
int listSize;
public:
PreviousDecorator(ListAsSLL* l) : Decorator(l)
{
listSize = 0;
head = 0;
tail = 0;
}
virtual void addToBeginning(int i)
{
Decorator::addToBeginning(i);
dnode * temp = new dnode;
temp->i = i;
if(head==0){
temp->next = 0;
tail = temp;
}else if(head == tail) {
temp->next = tail;
tail->prev = temp;
}
else{
temp->next = head;
tail->prev = temp;
}
temp->prev = 0;
head = temp;
listSize++;
}
virtual void print()
{
Decorator::print();
node* temp = head;
for (int i = 0; i < listSize; ++i) {
cout<<temp->i<<" "<<endl;
temp = temp->next;
}
}
friend class DLLIterator;
};
class ListAsDLL : public ListAsSLL
{
public:
virtual void addToBeginning(int i){}
virtual void print(){}
};
class DLLIterator
{
private:
ListAsDLL* dll;
public:
DLLIterator(ListAsDLL* dll)
{
this->dll = dll;
}
int getFirst()
{
return dll->head->i;
}
};
int main() {
ListAsSLL* dll = new PreviousDecorator(new ListAsDLL());
dll->addToBeginning(20);
DLLIterator* it = new DLLIterator((ListAsDLL*) dll);
cout<<it->getFirst()<<endl;
delete dll;
delete it;
return 0;
}
唯一の問題は、私はイテレータクラスにパラメータとしてListAsDLLに渡していますので、私はそれが飾られているクラスの保護された属性にアクセスすることができませんということです。したがって、私はdll-> head-> iにアクセスすることはできません。
まず、デコレータデザインパターンを正しく使用していますか?次に、友人クラスが装飾されているクラスの保護属性にどのようにアクセスできますか。
アクセスの質問については、 'ListAsDLL'クラスに' friend class DLLIterator; 'を追加することができます。 'class DLLIterator;'クラスは 'ListAsDLL'クラスの前に宣言されていなければなりません。 – Franck
@Franck dll-> head-> iにアクセスしようとすると、まだセグメンテーション違反が発生します。これは実行時に追加されるだけなので、コンパイル時には存在しないと見なされるからです。 – Keagansed
'ListAsSLL'が共通していても' PreviousDecorator * 'を' ListAsDLL * 'にキャストすることはできません。 'ListAsDLL'を読んだとき、未定義のフィールドを読み込んでいます。 – Franck