2010-07-01 86 views
2

我想寫這樣的代碼:如何定義一個可以返回指向自己的指針的函數?

/*something*/ Fn() { ... } 

int main() 
{ 
    /*something*/ fn = Fn; 
    while(fn) fn = fn(); 
    return 0; 
} 

是否有可能做到這一點是完全類型安全的方式?假設C,C++,D,C#,Java或任何其他靜態類型的語言。

+0

什麼是你的殘局? – 2010-07-01 00:37:40

+0

它使一個非常簡單的DFA引擎。或者用'vector ',一個NFA引擎 – BCS 2010-07-01 00:40:26

+0

可能重複的[Self referential type](http://stackoverflow.com/questions/3048689/self-referential-type)順便說一句,接受的答案不是你問題的答案。看第二個答案。 – 2010-07-01 00:48:17

回答

1

這裏是一個C#示例

delegate MyFunctionDelegate MyFunctionDelegate(); 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyFunctionDelegate fn = FN1; 
     while (fn!=null) 
      fn = fn(); 
    } 

    static MyFunctionDelegate FN1() 
    { 
     Console.WriteLine("FN1 called"); 
     MyFunctionDelegate returnDelegate = FN2; 
     return returnDelegate; 
    } 

    static MyFunctionDelegate FN2() 
    { 
     Console.WriteLine("FN2 called"); 
     return null; 
    } 
} 
+0

C#我認爲? – BCS 2010-07-01 00:58:09

+0

是的,對不起,我在我的原創中提到過。發佈並且必須進行格式編輯。在我看來,它在C/C++中更簡單一些,但C#爲您提供了強大的輸入。使用C/C++,指針可以指向任何地方。 – 2010-07-01 01:35:36

相關問題