Recursively call a function object

▼魔方 西西 提交于 2019-12-05 04:10:49
#include <iostream>

class factorial {
public:
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * (*this)(n-1);
  }
};

int main()
{
    std::cout << factorial()(5) << std::endl;
}

Works fine for me. Live example.

You can either use the name of the overloaded operator:

operator()(n-1);

or invoke the operator on the current object:

(*this)(n-1);

As DyP mentioned, you can call (*this)(n-1). However, it's odd to read, so you'd be better off splitting it out into a seperate calculate_factoral method and calling that instead

As several people have pointed out you can just use the (*this)(n - 1) syntax. But this syntax isn't exactly intuitive and a slightly better solution may be to factor out the actual implementation into another named method.

class factorial { 
public:
  int operator()(int n) {
    return impl(n);
  }
private:
  int impl(int n) { 
    // actual work here 
  }
};

You can either use explicit operator syntax:

class factorial {
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * operator()(n-1);
  }
};

Or dereference this:

class factorial {
  int operator()(int n) {
    if (n == 0)
      return 1;
    return n * (*this)(n-1);
  }
};

factorial surely?

I only know Java and a recursive factorial can be written as:

public class Factorial{

    public int factorial(int n) {
        return (n > 1) ? n * factorial(n-1) : 1;
    }
}

I assume the same principle applies.

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