Understanding the use of operator () (Function Object)

余生颓废 提交于 2021-02-11 14:25:11

问题


In this code below I can´t understand really well how can std::generate(v2.begin(), v2.end(), r) call the rand() if there isn´t the operator () in r or even any parameters on it.

class RandomInt
{
public:
    RandomInt(int a, int b);
    int operator()();
private:
    int limInf, limSup; // interval limits: [limInf..limSup]
};
//----------------------------------------------------------------------
RandomInt::RandomInt(int a, int b)
{
    limInf = a; limSup = b;
}
//----------------------------------------------------------------------
int RandomInt::operator()()
{
    return limInf + rand() % (limSup - limInf + 1);
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
int main() {
    srand((unsigned)time(NULL));
    std::vector<int> v2(10);
    int limInf, limSup;
    std::cout << "limInf ? "; std::cin >> limInf;
    std::cout << "limSup ? "; std::cin >> limSup;
    RandomInt r(limInf, limSup); //instantiates object and sets limits
    std::generate(v2.begin(), v2.end(), r);
    // ALTERNATIVE:
    // using an unnamed temporary that will be destroyed at the end of the call
    //generate(v2.begin(),v2.end(),RandomInt(limInf,limSup));
    displayVec("random numbers", v2);
    return 0;
}

来源:https://stackoverflow.com/questions/62116060/understanding-the-use-of-operator-function-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!