【发布时间】:2015-04-16 00:52:55
【问题描述】:
我对以下代码有疑问。
template <typename T>
struct DisplayElementKeepCount
{
int m_nCount;
DisplayElementKeepCount () { m_nCount = 0; }
void operator () (const T& element){++ m_nCount; cout<<element<<‘ ‘;}
};
调用时写成:
DisplayElementKeepCount <int> mResult;
mResult = for_each ( vecIntegers.begin (), vecIntegers.end (), DisplayElementKeepCount <int> () );
我不是很明白,因为operator()需要一个参数“元素”,但是调用的时候没有包含。为什么?
IsMultiple 的例子在调用的时候其实是给了一个参数。为什么这两个不同??
template <typename numberType>
struct IsMultiple
{
numberType m_Divisor;
IsMultiple (const numberType& divisor)
{
m_Divisor = divisor;
}
// The comparator of type: bool f(x)
bool operator () (const numberType& element) const
{
// Check if the dividend is a multiple of the divisor
return ((element % m_Divisor) == 0);
}
};
...
vector <int>::iterator iElement;
iElement = find_if ( vecIntegers.begin (), vecIntegers.end (),
IsMultiple <int> (4) );
【问题讨论】:
-
您的第二个示例是为
IsMultiple的构造函数提供参数,而不是operator()。operator()的参数被传递给算法内部的函子,用于范围内的每个元素。
标签: c++ operator-overloading functor function-object