2013-11-15 31 views
0

我正在寫一個簡單的動畫來繪製一個球從牆壁反彈。這裏是類:使用框架,錯誤的構造函數C++崩潰

class Ball{ 

private: 
int x,y; //position 
int vx,vy; //velocity 
int rad=20; //radius 
ofColor color; //color 

public: 
Ball(int a, int b, int c, int d,ofColor e); 
Ball(); 
void draw(); 
void move(); 
}; 

當我構建球5個參數一切正常,但是當我使用了一個不帶參數的崩潰:

Ball::Ball(){ 

x=int(ofRandomWidth()); 
y=int(ofRandomHeight()); 
vx=int(ofRandom(-10,10)); 
vy=int(ofRandom(-10,10)); 

int r=int(ofRandom(0,255)); 
int g=int(ofRandom(0,255)); 
int b=int(ofRandom(0,255)); 
ofColor a(r,g,b); 
color=a; 
} 

有什麼可以不對的構造?

ofRandom:

float ofRandom(float max) { 
return max * rand()/(RAND_MAX + 1.0f); 
} 

//-------------------------------------------------- 
float ofRandom(float x, float y) { 

float high = 0; 
float low = 0; 
float randNum = 0; 
// if there is no range, return the value 
if (x == y) return x;   // float == ?, wise? epsilon? 
high = MAX(x,y); 
low = MIN(x,y); 
randNum = low + ((high-low) * rand()/(RAND_MAX + 1.0)); 
return randNum; 
} 
+2

'ofRandom'函數是否返回浮點值?在這種情況下,您應該使用'static_cast'而不是'int'構造函數來使它們成爲'int'。 – noobProgrammer

+0

你可以將代碼發佈到ofRandom等嗎? – SamFisher83

+0

爲什麼在作業需要爲您做好這些工作時,您會進行明確的轉換? – tadman

回答

0

你必須寫在空構造即Ball()的身體。在這裏,你應該初始化所有的變量,以達到你決定的某個值。 否則這些整數將具有垃圾值或默認值0.

另外color是類ofColor的對象對不對?因此,在空構造,你應該也通過調用它的構造在構造函數初始化列表來初始化的color值,如:

Ball(): color()或取決於你寫一個參數的構造函數。

這些都是可能有可能與您的構造函數錯誤的東西,但因爲你沒有發佈的代碼,我不能說。

另一件事是你已經初始化了類內的變量rad。初始化構造函數中的所有變量總是好的,從不在類中。