【问题标题】:questions about function object in C++关于C++中函数对象的问题
【发布时间】: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


【解决方案1】:

在您的第一个示例中,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

【讨论】:

  • 感谢您的解释。但我在这里还有一个问题。根据您的评论,未调用 operator() ,仅调用了构造函数。对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多