如何在每个循环中传递成员函数?

zyy*_*osh 4 c++ foreach class

我试图使用std::for_each()而不是正常的for循环作为练习,但我无法将成员函数传递给for_each().

这是代码:

class Class
{
    public :
        void func (int a)
        {
            cout << a * 3 << " ";
        }
}ob1;

int main()
{
    int arr[5] = { 1, 5, 2, 4, 3 };
    cout << "Multiple of 3 of elements are : ";
    for_each(arr, arr + 5, ob1);
}
Run Code Online (Sandbox Code Playgroud)

仅当该成员函数为 时它才起作用void operator() (int a)。我不知道为什么不能传递任何其他成员函数for_each()

Rem*_*eau 5

您没有将任何类方法传递给for_each(),而是传递一个对象,该对象仅在该对象实现 时才起作用operator()

for_each()调用您的Class::func()方法,您需要:

  • operator()在你的班级中实施:

    class Class
    {
    public:
        void func (int a)
        {
            std::cout << a * 3 << " ";
        }
    
        void operator()(int a)
        {
            func(a);
        }
    }ob1;
    
    std::for_each(arr, arr + 5, ob1);
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用一个单独的委托来实现operator()调用您的类。