-
February 20th, 2013, 05:55 PM
#1
A question regarding stl set
Here is the code,
Code:
#include <set>
using namespace std;
class A
{
public:
void bar()
{
cout<<"bar"<<endl;
}
};
void foo(A& a)
{
a.bar();
}
int main()
{
set<A> setA;
A a;
for(set<A>::iterator it=setA.begin();it!=setA.end();++it)
{
a = *it;
foo(*it);
}
return 0;
}
If I call foo(*it), then I get an error " error C2664: 'foo' : cannot convert parameter 1 from 'const A' to 'A &' ". But if I call foo(a), then it would compile just fine. Why? What is the difference between a and *it. I thought they are basically the same. Thanks.
-
February 20th, 2013, 07:54 PM
#2
Re: A question regarding stl set
Because foo() could (potentially) modify the parameter that is passed.
So ... foo(*it) , could modify an element in the set (which is not allowed,
since it could mess up the ordering).
-
February 21st, 2013, 12:47 PM
#3
Re: A question regarding stl set
there is a difference...
a = *it; with foo(a)
assigns/copies *it into an existing object a. then you call foo on an object that is not const. which is ok.
in the foo(*it) case, you're trying to pass "const" *it to a function that epxects a modifiable object reference.
if you changed foo to foo(const A& a) then you could call foo(*it).
in this particular case, since foo() calls A::bar(), you would also have to change bar to void bar() const;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|