Problem Implementing Observer Pattern : “Member reference base type ________ is not a structure or union”

可紊 提交于 2019-12-06 23:58:21

问题


I've been implementing a barebones observer pattern and am stuck on a somewhat cryptic error: "Member reference base type 'Observer *' is not a structure or union". I assume this has something to do with my use of templates, with which I'm still fairly uncomfortable. Here is the offending code (most cons/destructors removed to simplify things):

Subject interface:

class Subject { 
public:
    virtual void notify();
private:
    list< Observer * > m_observers; 
};

Subject implementation:

void Subject::notify() {
    list< Observer * >::iterator i;

    for ( i = m_observers.begin(); i != m_observers.end(); i++ ) {
        *i->update( this );                        // ERROR !!! ERROR
}

Observer abstract interface:

class Observer {
public:
    virtual ~Observer();
    virtual void update( Subject * changedSubject ) = 0;

protected:
    Observer();
};

Concrete Observer interface:

class ConcreteObserver: public Observer {

public:
    ConcreteObserver( ConcreteSubject * );
    virtual ~ConcreteObserver();

    virtual void update( Subject * changedSubject );

private:
    ConcreteSubject * m_subject;
};

Concrete Observer implementation:

void ConcreteObserver::update( Subject * changedSubject ) {
    if ( changedSubject == m_subject ) {
        report();
    }
}

If anyone could help identify this problem, I would greatly appreciate it.

Cheers, Nick


回答1:


The problem is with the operator precedence. Instead of:

*i->update( this );

Use:

(*i)->update( this );

Otherwise, it will be interpreted as *(i->update( this )), which tries to call a method on a pointer, resulting in the error message.



来源:https://stackoverflow.com/questions/6683451/problem-implementing-observer-pattern-member-reference-base-type-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!