问题实现观察者模式:“成员引用基类型________不是结构或联合体” [英] Problem Implementing Observer Pattern : "Member reference base type ________ is not a structure or union"
问题描述
我一直在实现一个准系统观察者模式,并且停留在一个有点神秘的错误:
成员引用基类型Observer *'不是一个结构或联合。我假设这与我使用的模板有关,我仍然相当不舒服。这里是冒犯的代码(最简单的消除了大部分cons / destructors简化的东西):
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):
主题界面:
class Subject {
public:
virtual void notify();
private:
list< Observer * > m_observers;
};
主题实施:
void Subject::notify() {
list< Observer * >::iterator i;
for ( i = m_observers.begin(); i != m_observers.end(); i++ ) {
*i->update( this ); // ERROR !!! ERROR
}
Observer抽象接口:
Observer abstract interface:
class Observer {
public:
virtual ~Observer();
virtual void update( Subject * changedSubject ) = 0;
protected:
Observer();
};
具体观察者界面:
class ConcreteObserver: public Observer {
public:
ConcreteObserver( ConcreteSubject * );
virtual ~ConcreteObserver();
virtual void update( Subject * changedSubject );
private:
ConcreteSubject * m_subject;
};
具体观察者实施:
void ConcreteObserver::update( Subject * changedSubject ) {
if ( changedSubject == m_subject ) {
report();
}
}
如果任何人可以帮助识别这个问题,非常感谢。
If anyone could help identify this problem, I would greatly appreciate it.
干杯,
Nick
Cheers, Nick
推荐答案
问题是用操作符优先级。而不是:
The problem is with the operator precedence. Instead of:
*i->update( this );
使用:
(*i)->update( this );
否则,将被解释为 *(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.
这篇关于问题实现观察者模式:“成员引用基类型________不是结构或联合体”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!