vector 题目Observer

出错代码:


#ifndef _OBSERVER
#define _OBSERVER
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;

class Observer {
     public:
          virtual ~Observer() {}
          virtual void notify() = 0;
};

class ObserverA : public Observer {
     public:
         void notify() {
             cout << "ObserverA is notified that Subject change." << endl;
         }
};

class ObserverB : public Observer {
     public:
         void notify() {
             cout << "ObserverB is notified that Subject change." << endl;
         }
};

class Subject {
     public:
         void registerObserver(Observer* ob) {
             obCo.push_back(*ob);   //instantiated from here 不能将容器类型定义为类,而应定义为类的指针,原因不明
         }
         void unregisterObserver(Observer* ob) {
              vector<Observer>::iterator it;
              for (it = obCo.begin(); it != obCo.end(); it++)
                 if (*it == ob)
                    obCo.erase(it);  //这里应该跳出循环
         }
         void notifyObservers() {
             vector<Observer>::iterator it;
             for (it = obCo.begin(); it != obCo.end(); it++)
                      (*it).notify();
         }
     private:
         vector<Observer> obCo;   //类型定义为Observer*
}  //类的分号啊!!!不要再忘了

#endif

标程:

#ifndef Observer_Observer_h
#define Observer_Observer_h
#include <iostream>
#include <vector>
using namespace std;
 
class Observer {
  public:
    virtual ~Observer() {
    }
    virtual void notify() = 0;
};
 
class ObserverA : public Observer {
  public:
    virtual void notify() {
        cout << "ObserverA is notified that Subject change." << endl;
    }
    virtual ~ObserverA() {
    }
};
 
class ObserverB : public Observer {
  public:
    virtual void notify() {
        cout << "ObserverB is notified that Subject change." << endl;
    }
    virtual ~ObserverB() {
    }
};
 
class Subject {
  private:
    vector<Observer*> observers;
  public:
    Subject() {
    }
    void registerObserver(Observer* observer) {
        observers.push_back(observer);
    }
 
    void unregisterObserver(Observer* observer) {
        vector<Observer*>::iterator itr = observers.begin();
        while (itr != observers.end()) {
            if (*itr == observer) {
                observers.erase(itr);
                break;
            }
            itr++;
        }
    }
 
    void notifyObserver() {
        for (int i = 0; i < observers.size(); i++)
            observers[i] -> notify();
    }
};
 
#endif


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值