2011-12-15 27 views
2

我試圖實現定義爲in this answer的隨機數生成器。至少從我的知識來看,至少應該如何實現第一行static unsigned long x=123456789, y=362436069, z=521288629;,因爲它在功能之外被顯示出來有一些含糊不清的地方。我以爲這是打算作爲一個類的成員,從而實現了它:在類成員上使用`^ =`和`<<`時出現C++總線錯誤`unsigned long`

class rng2{ 

public:  

    unsigned long x, y, z; 
    rng2() : x(123456789), y(362436069), z(521288629) {} 

    unsigned long xorshf96(void) {   //period 2^96-1 

     //static unsigned long x=123456789, y=362436069, z=521288629; 

     unsigned long t; 
     x ^= x << 16;   //BUS ERROR, debug mode 
     x ^= x >> 5; 
     x ^= x << 1; 

     t = x; 
     x = y;     //SEG FAULT, release mode 
     y = z; 
     z = t^x^y; 

     return z; 
    } 

}; 

int main() 
{ 
    rng2 rand2; 
    rng2 * prand; 

    for(long d =0; d < 10000; d++) 
     cout << "\n" << (*prand).xorshf96(); 
} 

出於某種原因,這給了我錯誤的注意位置,這取決於我和編譯的模式。但是,如果我註釋掉成員變量和構造函數並使用靜態變量,則一切正常。如果這是正確的代碼,我不明白爲什麼它在鏈接上顯示的不同,並且無論哪種方式,我不知道錯誤發生的原因。

回答

4

您正在使用* prand,但未初始化prand。

2

這是因爲prand指針從不分配,但僅用於使用。當使用static時,變量no datamember被訪問,這就是爲什麼你沒有得到總線錯誤。你應該明確地指定你的指針在你的主函數中有效的值。像這樣

rng2 * prand = new rng2(); 
+0

這聲明瞭一個指向rng2的指針,叫做prand並將它指定給一個指向rng2對象的新實例的指針。應該工作吧?我不明白你的評論。 – vidstige 2011-12-15 08:55:13

+0

哦,對,thansk! – vidstige 2011-12-15 09:08:32

2

prandwild pointer

變化:

int main() 
{ 
    rng2 rand2; 
    rng2 * prand; 

    for(long d =0; d < 10000; d++) 
     cout << "\n" << (*prand).xorshf96(); 
} 

到:

int main() 
{ 
    rng2 rand2; 
    rng2 * prand = &rand2; 

    for(long d =0; d < 10000; d++) 
     cout << "\n" << (*prand).xorshf96(); 
} 

或更好的只是:

int main() 
{ 
    rng2 rand2; 

    for(long d =0; d < 10000; d++) 
     cout << "\n" << rand2.xorshf96(); 
} 
2
rng2 * prand; 

你完全肯定這是真正的代碼?考慮到你沒有初始化這個指針並在以後解除引用,這個錯誤非常明顯。

相關問題