装饰器设计模式,分段错误
Decorator Design Pattern, Segmentation fault
我想实现装饰器设计模式。但是,我的代码给了我Segmentation fault
错误。我尝试使用 -g
标志编译它,然后用 gdb
检查它。 gdb
仅显示错误在action
方法中的某个地方,但我不明白在哪里以及为什么。
#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;
}
原因是无限回避。
在 CConcreteDecorator3 中的操作方法中,而不是:
int w = action();
您可能应该使用:
int w = Decorator::action();
此外...
- 您的装饰器类泄漏。您没有带有删除的析构函数。 使用
std::vector<int>
代替int *
i_array 和 std::unique_ptr 被认为是很好的做法,CComponent * c;
除非你无法避免,否则不要打扰使用 new/delete。- 您的 CComponent 需要一个虚拟析构函数。如果你谷歌多态性和虚拟析构函数,你会发现很多解释。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?