【发布时间】:2012-03-11 22:02:57
【问题描述】:
我是学习函子的 C++ 菜鸟。我有如下代码(注意 - 这不是我的作业,我已经过去了!)。
它确实在控制台上打印 0 1 2 3 4 5 6 7 8 9
如果函子是按值而不是按引用/指针调用的,我看不出它如何保持这个对象的状态(n 的值)
编辑: 我想在这里(示例 1),因为函子是由 Value 调用的,并且构造函数每次都将 n 初始化为零。所以它应该在开始时总是为零,然后它应该递增到 1 并返回 1。它是如何打印 0 1 2 3 4 5 6 7 8 9
示例 1]
class g
{
public:
g():n(0){}
int operator()() { return n++; }
int n;
};
;
int main()
{
int a[10];
g v1;
std::generate(a, a+10, g());//This passes a functor to generate
//EDIT - this will print 0 1 2 3 4 5 6 7 8 9**
std::copy(a, a+10, std::ostream_iterator<int>(std::cout, " "));
getchar();
return 0;
}
因为我已经看到下面的代码使用仿函数内的引用变量来保留状态,here 并使用该概念开发了一个简单的代码,如下所示:
示例 2]
class CountingFunctor
{
public:
CountingFunctor() : _counter(0) {}
int getCounter(void) const {return(_counter);}
void operator () (Contained item) {if(item.getShouldBeCounted()) _counter++;}
private:
int _counter;
};
#endif
//this class uses references to maintain state in the functor
class CountingFunctor
{
public:
CountingFunctor(int &elem) : _counter(elem) {_counter=0;}
int getCounter(void) const {return(_counter);}
void operator () (Contained item) {if(item.getShouldBeCounted()) _counter++;}
private:
int &_counter;
};
int main()
{
vector<Contained> Container(10);
Container[3].setShouldBeCounted(false);
Container[9].setShouldBeCounted(false);
int elem;
CountingFunctor CountAllWhoShouldBe(elem);
std::for_each(Container.begin(), Container.end(), CountAllWhoShouldBe);
std::cout << CountAllWhoShouldBe.getCounter() << " items should be counted." << std::endl;
getchar();
}
问题是
所以函子自己维护其对象的状态,即不需要任何引用变量,如示例 2 所示
或者示例 1 中的代码工作正常,因为 std::generate() 通过引用/指针调用函子?
欢迎进一步阅读材料。
【问题讨论】: