C ++使用框架崩溃,构造函数错误
c++ crashes using frameworks, bad constructor
我正在写一个简单的动画来画一个从墙上弹跳的球。这是类:
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
。在构造函数中初始化所有变量总是好的,而不是在类中初始化。
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- C++ OpenCV 卡尔曼滤波器构造函数错误
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- C++ 中常量属性的初始化构造函数错误
- STL向量上出现奇怪的复制构造函数错误
- C++ 乘法定义的构造函数错误消息似乎错误
- 通过构造函数错误地播种梅森扭曲
- C++ 多态构造函数错误;标识符未定义
- 类组合中的构造函数错误
- C++中的构造函数错误
- 构造函数错误:错误:数字常量之前的预期“”,“”或“..”
- 这个奇怪的复制构造函数错误抱怨的是什么
- Singleton子类构造函数错误
- 默认构造函数错误 (C++)
- 基类构造函数错误
- 初始化列表构造函数错误带有CRTP
- C++可能存在写入位置的构造函数错误冲突
- 构造函数错误:需要标识符
- 复制构造函数错误:对象的类型限定符与成员函数不兼容