Pregunta

How do I call a function object from within itself? Seems I cannot use this. Example:

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

What do I place at ???

¿Fue útil?

Solución

#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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top