[英]Problem Implementing Observer Pattern : “Member reference base type ________ is not a structure or union”
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".我一直在实现准系统观察者模式,但遇到了一个有点神秘的错误:“成员引用基类型'Observer *'不是结构或联合”。 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干杯,尼克
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.否则,它将被解释为
*(i->update( this ))
,它试图调用指针上的方法,从而导致错误消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.