I want to implement the Decorator design pattern. However, my code gives me Segmentation fault
error. I tried to compile it using the -g
flag and then check it with gdb
. gdb
shows only that the error is somewhere inside the action
method, but I do not understand where and why.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class CComponent
{
protected:
int * i_array;
int i_size;
public:
CComponent(int i_size)
{
this->i_size=i_size;
i_array= new int[i_size];
for(int i=0; i<i_size; i++)
{
i_array[i]=0;
}
}
virtual int action() = 0;
~CComponent()
{
delete i_array;
}
int get_i_size()
{
return i_size;
}
int get_array_at(int index)
{
return i_array[index];
}
};
class CConcreteCComponent : public CComponent
{
public:
CConcreteCComponent(int i_size) : CComponent(i_size) { }
int action()
{
for(int i=0; i<i_size; i++)
{
i_array[i] = rand() % 100;
cout<< i_array[i] << " " << endl;
}
return 0;
}
};
class Decorator : public CComponent
{
protected:
CComponent * c;
public:
Decorator(int i_size) : CComponent(i_size)
{
c = new CConcreteCComponent(100);
}
int action()
{
return c->action();
}
};
class CConcreteDecorator3 : public Decorator
{
public:
CConcreteDecorator3(int i_size) : Decorator(i_size)
{
}
int action()
{
int w = action();
for(int i=0; i<c->get_i_size(); i++)
if(c->get_array_at(i) % 2 == 0)
return w;
return w + 50;
}
};
class CConcreteDecorator1 : public Decorator
{
public:
CConcreteDecorator1(int i_size) : Decorator(i_size)
{
}
int action()
{
int w = action();
if(c->get_array_at(0) == 0 && c->get_array_at(i_size -1) == 0)
return w + 100;
return w;
}
};
class CConcreteDecorator2 : public Decorator
{
public:
CConcreteDecorator2(int i_size) : Decorator(i_size)
{
}
int action()
{
int w = action();
if(c->get_i_size() > 7)
return w + 150;
return w;
}
};
int main()
{
Decorator * d = new CConcreteDecorator3(100);
Decorator * d2 = new CConcreteDecorator1(100);
Decorator * d3 = new CConcreteDecorator2(100);
int res;
res = d->action();
cout << "res :" << res << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire