C ++使用框架崩溃,构造函数错误

c++ crashes using frameworks, bad constructor

本文关键字:构造函数 错误 崩溃 框架      更新时间:2023-10-16

我正在写一个简单的动画来画一个从墙上弹跳的球。这是类:

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::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;
}

这个构造函数可能有什么问题?

随机:

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;
} 

你必须编写空构造函数的主体,即 Ball() .在这种情况下,您应该将所有变量初始化为您将决定的某个值。否则,这些整数将具有垃圾值或默认值 0。

还有color是类ofColor的对象吧?因此,在 null 构造函数中,您还应该通过在构造函数初始值设定项列表中调用其构造函数来初始化 color 的值,例如:

Ball(): color()或参数化构造函数,具体取决于您编写的内容。

这些是您的构造函数可能存在错误的东西,但由于您尚未发布代码,我不能说。

另一件事是你已经初始化了类内部的变量rad。在构造函数中初始化所有变量总是好的,而不是在类中初始化。