C++ c++;使用框架崩溃,构造函数错误
我正在写一个简单的动画来画一个从墙上弹起的球。下面是课堂:C++ c++;使用框架崩溃,构造函数错误,c++,constructor,openframeworks,C++,Constructor,Openframeworks,我正在写一个简单的动画来画一个从墙上弹起的球。下面是课堂: 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时
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::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()
。在这种情况下,您应该将所有变量初始化为您将决定的某个值。
否则,这些int将具有垃圾值或默认值0
另外,color
是属于颜色的类的对象,对吗?因此,在空构造函数中,您应该通过在构造函数初始值设定项列表中调用其构造函数来初始化color
的值,如:
Ball():color()
或参数化构造函数,具体取决于您编写的内容
这些都是你的构造函数可能出错的地方,但是因为你还没有发布代码,我不能说
另一件事是您已经在类内初始化了变量rad
。初始化构造函数中的所有变量总是好的,而不是在类中。随机函数的是否返回浮点值?在这种情况下,您应该使用static_cast
而不是int
构造函数来将它们的大小写为int
s。您可以将代码发布到ofRandom等吗?当赋值应该为您处理时,为什么要进行显式转换?是的,它返回浮点