これは初心者のC++の質問です。ウィキペディアの「関数オブジェクト」の記事を読んでいました。この記事には、次のようなC++の例があります。
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));
}
2つの質問があります:
countが参照型ではなく通常の変数であるのに、なぜコンパイルに失敗するのですか?デモ
コンパイルに失敗するのはなぜですか?次のように変更し
ctor
ますか?デモprintClass(int &n) { count = n; }
ありがとう。
編集:説明してくれてありがとう。次のバージョンも機能するようです。お互いを選ぶ理由はありますか?
struct printClass {
int count;
printClass(int n) { count = n; }
void operator()(int &i) {
count++;
cout << i << "[" << count << "] ";
}
};
編集:iammilindの返信に基づいて、これはを使用しても機能する3番目のバージョンですconst_cast<int &>
。
struct printClass {
int count ;
printClass(int n) : count(n) {}
void operator()(int &i) const {
const_cast<int &>(count)++;
cout << i << "[" << count << "] ";
}
};