This is a newbie C++ question. I was reading the "Function object" article in Wikipedia. The article has an example in C++ similar to the following:
struct printClass {
int &count;
printClass(int &n) : count(n) {}
void operator()(int &i) const {
count++;
cout << i << "[" << count << "] ";
}
};
int main(int argc, char** argv) {
vector<int> a(5, 7);
a[4] = -1;
a.resize(10, 3);
int state = 0;
for_each(a.rbegin(), a.rend(), printClass(state));
}
I have 2 questions:
Why does it fail to compile when count is a regular variable not a reference type? Demo
Why does it fail to compile it I change the
ctor
to the following? DemoprintClass(int &n) { count = n; }
Thanks.
EDIT: Thanks for explaining. I see that the following version works, too. Is there a reason for chosing one over another?
struct printClass {
int count;
printClass(int n) { count = n; }
void operator()(int &i) {
count++;
cout << i << "[" << count << "] ";
}
};
EDIT: Based on iammilind's reply, here is the 3rd version that works too using const_cast<int &>
.
struct printClass {
int count ;
printClass(int n) : count(n) {}
void operator()(int &i) const {
const_cast<int &>(count)++;
cout << i << "[" << count << "] ";
}
};