1. 程式人生 > >c++ 成員函式尾遞迴

c++ 成員函式尾遞迴


#include <iostream>

int factorial_tail(int n, int first, int second)
{
    if (n == 1)
    {
        return second;
    }
    else
    {
        return factorial_tail(n - 1, second, first + second);
    }
}

class TailRecurison
{
public:
    void run(int i)
    {
        if (i == 0)
        {
            return
; } std::cout << i << std::endl; --i; return run(i); } static void static_run(int i) { if (i == 0) { return; } std::cout << i << std::endl; --i; return static_run(i); } }; void
testTail() { int ret = factorial_tail(10, 0, 1); std::cout << "result:" << ret << std::endl; } void testMemberTailRecursion() { TailRecurison *pTest = new TailRecurison; pTest->run(100); std::cout << "over" << std::endl; } void testStaticMemberTailRecursion() { TailRecurison *pTest = new
TailRecurison; pTest->static_run(100); std::cout << "over" << std::endl; } int main(int, char**) { testTail(); testMemberTailRecursion(); testStaticMemberTailRecursion(); return 0; }