简单策略模式中的错误

时间:2015-10-01 11:09:17

标签: c++ segmentation-fault

最近,我在C ++中练习策略模式。这是代码。

#include <iostream>

using namespace std;

class Isquare {
public:
    virtual void draw()=0;       
};

class circle:public Isquare {
public:
  void draw() {
       cout<<"circle"<<endl;
  }
};

class rectangle:public Isquare {
public:
  void draw(){
       cout<<"rectangle"<<endl;
  }      
};

class graph {
  Isquare* ss;
public:
  graph() {
    ss = 0;     
  } 

  void setGraph(Isquare* Is) {
      ss = Is;      
  }
  void draw(){
      ss->draw();
  }          
};

int main(void) {   
  graph* GG;
  GG->setGraph(new circle);
}

这是正确的,并且在此代码中没有错误。 但我也尝试了另一种方法来实现它,代码如下:

#include <iostream>

using namespace std;

class Isquare {
public:
  virtual void draw()=0;       
};

class circle:public Isquare {
public:
  void draw() {
       cout<<"circle"<<endl;
  }
};

class rectangle:public Isquare {
public:
  void draw(){
      cout<<"rectangle"<<endl;
  }      
};

class graph {
  Isquare* ss;
public:
  graph(){
     ss = 0;     
  } 

  void setGraph(Isquare* Is){
     ss = Is;      
  }   
  void draw(){
     ss->draw();
  }
};

int main(void) {   
  graph* GG;
  circle _circle; 
  GG->setGraph(&_circle);//why it core down???   
}

运行后我得到了分段错误.... 为什么案例分段错误? THX!

2 个答案:

答案 0 :(得分:4)

您没有为GG分配内存

答案 1 :(得分:2)

您忘了创建GG对象。

 graph* GG;

应该是

 graph* GG = new graph();