How to invoke member functions of an object in set

X

xiaohuamao

Hi,all. I am a beginner in STL. When i compile the following code, i
meet an error.
The error code is "error C2662: 'vPrint' : cannot convert 'this'
pointer from 'const class son' to 'class son &'.
What should i do to make it work? Remove the constness? How to?

#include <set>
using namespace std;

class son {
private:
int i;
public:
son(int num) : i(num) {}
int i4GetNum() {return i;}
void vPrint() {cout << "Hi,Son " << i << " !" << endl;}
};

struct sonCmp : public binary_function<son, son, bool>{
bool operator () (son n1, son n2) const{
return n1.i4GetNum() < n2.i4GetNum();
}
};

int main()
{
set<son, sonCmp> setSon;
set<son, sonCmp>::iterator iter;
for (int i = 0; i<10; i++)
setSon.insert(son(i));

// for_each(setSon.begin(), setSon.end(), mem_fun_ref((&son::vPrint)));
for (iter = setSon.begin(); iter != setSon.end(); ++iter)
iter->vPrint();
return;
}
 
M

Martin Ambuhl

xiaohuamao said:
Hi,all. I am a beginner in STL.

STL (and your code) is in C++, not C. While there is an ancestral link,
C and C++ split apart before there was even a standard for either.
These languages are sufficiently different and have sufficiently
different attitudes about the right ways to do things, that it makes no
sense to ask about C++ in < The good news is that
there is <for people who have C++ questions and who
before posting are willing to check the FAQ and follow that newsgroup
for several weeks (which can be done in much less time with the archive
at Google groups).

An example of why you should follow those simple rules of etiquette in
newsgroups: had you checked the FAQ for this newsgroup or followed it
for any time, you would have known not to post here and not wasted your
time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top