关于C ++中函数对象的问题

时间:2015-04-16 00:52:55

标签: c++ operator-overloading functor function-object

我对以下一段代码有疑问。

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()需要一个参数“element”,但在调用时它不包括在内。为什么呢?

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) );

1 个答案:

答案 0 :(得分:2)

在您的第一个示例中,DisplayElementKeepCount有一个默认构造函数(它接受零参数)并且您正在使用它。

for_each ( vecIntegers.begin (), vecIntegers.end (), DisplayElementKeepCount <int> () );
                                                                   //  Constructor ^^

如果你打电话给operator(),它将如下所示。

DisplayElementKeepCount<int>()(5)
             // Constructor ^^
                           // ^^^ calling operator() on the unnamed instance

在第二个示例中,IsMultiple有一个构造函数,它只接受一个参数。

find_if ( vecIntegers.begin (), vecIntegers.end (), IsMultiple <int> (4) );
                                                      // Constructor ^^^

同样,如果你打电话给operator(),它将如下所示。

IsMultiple<int>(4)(2)
// Constructor ^^^
               // ^^^ calling operator() on the unnamed instance
相关问题