Reputation: 265
i was implementing observer design pattern in c++.It is a very simple application where observer registers and is informed about the stock prices whenever they are updated.
i am getting following error while compiling , unfortunately not able to fix it.I hope you guys will help.
compiler Error :-
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 *'
My code is the following :-**
#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);
}
Upvotes: 0
Views: 223
Reputation: 5118
end()
should be called on the container, not the iterator, at line 54myset
is a set<observer *>
, so after dereferncing an iterator, you get an observer*
, at line 56 Try this:
virtual void notifyAll(){
string s=getNewPrice();
set<observer *>::iterator it;
for(it=myset.begin();it!=myset.end();++it)
//^^^^^ HERE
{
(*it)->update(s); // AND HERE
}
}
Additionally, you probably want to change your observer signature to be:
class observer {
public:
virtual void update(const string& s) = 0;
virtual void remove();
};
and update the rest accordingly.
Upvotes: 2