此运算符重载函数重载是什么?

用户名

我正在查看CMBC源代码,并遇到了以下代码片段:

void goto_symext::operator()(const goto_functionst &goto_functions)
{
  goto_functionst::function_mapt::const_iterator it=
    goto_functions.function_map.find(goto_functionst::entry_point());

  if(it==goto_functions.function_map.end())
    throw "the program has no entry point";

  const goto_programt &body=it->second.body;

  operator()(goto_functions, body);
}

我以前从未见过operator()(args)语法,而谷歌搜索似乎并没有产生任何结果。

贾斯汀时间-恢复莫妮卡

那就是函数调用运算符,它使您可以制作类似函数的对象。

struct Functor {
    bool operator()(int a, int b = 3);
};

bool Functor::operator()(int a, int b /* = 3 */) {
    if ((a > (2 * b)) || (b > (2 * a))) {
        return true;
    } else {
        return false;
    }
}

// ...

Functor f;
bool b = f(5); // Calls f.operator()(5, 3).
bool c = f(3, 5);

它的好处是,您可以将状态信息保存在类似函数的对象的字段中,并且,如果有必要,您可以在对象内隐藏运算符的重载版本,而不必暴露它们。

class Functor {
    int compareTo;

    public:
        Functor(int cT);

        bool operator()(int a);
        bool operator()(char c);
};

Functor::Functor(int cT) : compareTo(cT) { }

bool Functor::operator()(int a) {
    if ((a > (2 * compareTo)) || (compareTo > (2 * a))) {
        return true;
    } else {
        return false;
    }
}

bool Functor::operator()(char c) { return false; }

它可以用来简化编写可以接受任何函数的代码,而不必依赖于函数指针。[在这方面,当与模板结合使用时,它特别好用。]

有关更多信息,请参见此处此处

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章