问题
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