我試圖實現定義爲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();
}
出於某種原因,這給了我錯誤的注意位置,這取決於我和編譯的模式。但是,如果我註釋掉成員變量和構造函數並使用靜態變量,則一切正常。如果這是正確的代碼,我不明白爲什麼它在鏈接上顯示的不同,並且無論哪種方式,我不知道錯誤發生的原因。
這聲明瞭一個指向rng2的指針,叫做prand並將它指定給一個指向rng2對象的新實例的指針。應該工作吧?我不明白你的評論。 – vidstige 2011-12-15 08:55:13
哦,對,thansk! – vidstige 2011-12-15 09:08:32