代码之家  ›  专栏  ›  技术社区  ›  Lion King

应用观察者模式时发生错误

  •  1
  • Lion King  · 技术社区  · 7 年前

    我有以下代码:

    class ISubscriber;
    class News {
    public:
        float getVersion() { return this->version; }
        void setVersion(float state) { this->version= state; this->notifyAllSubscribers(); }
        void attach(ISubscriber *observer) { this->subscribers.push_back(observer); }
        void notifyAllSubscribers() {
            for (vector<ISubscriber*>::iterator it = subscribers.begin(); it != subscribers.end(); it++){
                (*(*it)).update();
            }
        }
    private:
        vector<ISubscriber*> subscribers;
        float version;
    };
    
    class ISubscriber {
    public:
        News *news;
        virtual void update() = 0;
    };
    
    class Subscriber1 : public ISubscriber {
    public:
        Subscriber1(News *news) { this->news = news; this->news->attach(this); }
        void update() override { cout << "Subscriber1: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }
    
    };
    
    class Subscriber2 : public ISubscriber {
    public:
        Subscriber2(News *news) { this->news = news; this->news->attach(this); }
        void update() override { cout << "Subscriber2: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }
    
    };
    
    
    int main(int argc, char *argv[]) {
        News newspaper;
        newspaper.setVersion(2.1f);
    
        Subscriber1 sb1(&newspaper);
        Subscriber2 sb2(&newspaper);
        return 0;
    }
    

    但奇怪的错误发生了:

    第一个错误指向此代码 (*(*it)).update(); 在里面 news 上课。 为什么会发生这些错误,原因是什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   songyuanyao    7 年前

    (*(*it)).update(); 需要类型 ISubscriber 完整地说,仅仅靠远期申报是不够的。

    你可以改变对 ISubscriber公司 News ,并给出 新闻 在那之前。

    class News;
    class ISubscriber {
    public:
        News *news;
        virtual void update() = 0;
    };
    
    class News {
    public:
        float getVersion() { return this->version; }
        void setVersion(float state) { this->version= state; this->notifyAllSubscribers(); }
        void attach(ISubscriber *observer) { this->subscribers.push_back(observer); }
        void notifyAllSubscribers() {
            for (vector<ISubscriber*>::iterator it = subscribers.begin(); it != subscribers.end(); it++){
                (*(*it)).update();
            }
        }
    private:
        vector<ISubscriber*> subscribers;
        float version;
    };