传递派生类指针C ++时出现运行时错误

时间:2013-03-18 18:18:50

标签: c++ pointers vector segmentation-fault

在尝试将对象的指针添加到另一个对象的实例中的向量时,我遇到了一个seg错误。我一次向向量添加多个指针,第一个指针有效但第二次尝试不断抛出seg错误。

class Observer {
  Observer();
  observe();
};

class Subject {
  std::vector<Observer*> *observers;
  std::string name;

  Subject();
  virtual std::string getName();
  virtual void addObserver(Observer *observer) {
    observers->push_back(observer);
  }
};

class Base : public Subject {
  Base(std::string newName) { name = newName; }
};

class Derivative : public Subject, public Observer {
  float a;
  float b;
  float c;
  Derivative(a, b, c) { this->a = a; this->b = b; this->c = c; }

};

class Board : public Base {
   Base *base;

   Board(std::string newName, Base *newBase) { name = newName; base = newBase; }

   void initializeDerivatives(int start, int end) {
     for (int i = start; i <= end; ++i) {
       addObserver(new Derivative(start, start + 1, start + 2)); //works
       base->addObserver(new Derivative(start, start + 1, start + 2)); //THIS WORKS
       addObserver(new Derivative(start, start + 2, start + 3)); //works
       base->addObserver(new Derivative(start, start + 2, start + 3)); //seg fault here
     }
   }
};

int main() {
  Base myBase("MYBASE");
  Board myBoard("MYBASE", myBase);

  myBoard.initializeDerivatives(1, 10);
}

当我将myBoard和myBase声明为指针时,我早先遇到了seg错误:     Base * myBase = new Base(“MYBASE”);     Board * myBoard =新董事会(“MYBASE”,myBase);

我不确定为什么那是因为我认为使用new运算符实际上会初始化对象的实例。更改它以使实际对象仍允许我向观察者向量添加一个指针,但第二个指针不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

class Subject中,您应该更改此内容:

std::vector<Observer*> *observers;

对此:

std::vector<Observer*> observers;

作为指针,您的代码不会显示指针在任何地方被初始化。如果在构造函数中 初始化,则可能会发生内存泄漏,因为Subject没有析构函数。