我在c ++中实现了观察者设计模式。这是一个非常简单的应用程序,观察者注册并在更新时了解股票价格。
我在编译时遇到以下错误,遗憾的是无法修复它。我希望你们能帮忙。
编译错误: -
observer.cpp: In method `void StockGrabber::notifyAll()':
observer.cpp:54: no matching function for call to `__rb_tree_iterator<observer *
,observer *const &,observer *const *>::end ()'
observer.cpp:56: request for member `update' in `(&it)->__rb_tree_iterator<obser
ver *,observer *const &,observer *const *>::operator *<observer *, observer *con
st &, observer *const *>() const()', which is of non-aggregate type `observer *'
我的代码如下: - **
#include<iostream>
#include<map>
#include<set>
#include<string>
using namespace std;
class observer{
public:
virtual void update(string s) = 0;
virtual void remove();
};
class subject{
public:
virtual void Register(observer *o);
virtual void UnRegister(observer *o);
virtual void notifyAll();
};
class StockGrabber : public subject
{
map<string,double> mymap;
set<observer *> myset;
string getNewPrice()
{
string s="";
map<string,double>::iterator it;
for(it=mymap.begin();it!=mymap.end();++it)
{
s=s+it->first+" - "+to_string(it->second)+"\n";
}
return s;
}
public:
virtual void Register(observer *o){
myset.insert(o);
}
virtual void UnRegister(observer *o){
myset.erase(o);
}
virtual void notifyAll(){
string s=getNewPrice();
set<observer *>::iterator it;
for(it=myset.begin();it!=it.end();++it)
{
(*it).update(s);
}
}
void setPrice(string stock,double price)
{
mymap[stock]=price;
}
};
class stockObserver : public observer
{
subject *stockGrabber;
public:
stockObserver(subject *sobj)
{
stockGrabber=sobj;
sobj->Register(this);
}
void remove()
{
stockGrabber->UnRegister(this);
}
virtual void update(string s){
cout<<"New Update\n";
cout<<s;
}
};
void main()
{
StockGrabber *stockgrabber=new StockGrabber();
stockObserver *ob1 = new stockObserver(stockgrabber);
stockgrabber->setPrice("google",21.43);
stockgrabber->setPrice("apple",21.43);
}
答案 0 :(得分:2)
end()
应该在容器上调用,而不是迭代器,在第54行myset
是set<observer *>
,因此在解除迭代器后,您会在第56行获得observer*
试试这个:
virtual void notifyAll(){
string s=getNewPrice();
set<observer *>::iterator it;
for(it=myset.begin();it!=myset.end();++it)
//^^^^^ HERE
{
(*it)->update(s); // AND HERE
}
}
此外,您可能希望将观察者签名更改为:
class observer {
public:
virtual void update(const string& s) = 0;
virtual void remove();
};
并相应地更新其余部分。