C++, Variables reverting to initial values
I have a C++ class, shapeObject, that is somewhat complicated but this question is only regarding two particular fields of the class, dX and dY.
header:
class shapeObject{
public:
shapeObject();
...
private:
float dX, dY;
...
};
cpp file:
shapeObject::shapeObject(){
...
dX = 0;
dY = 0;
...
}
These fields are only modified by one function, which adds or subtracts a small float value开发者_Python百科 to dX or dY. However, the next time the value of dX or dY is read, they have reverted back to their original value of 0.0 .
Since the fields are not being modified anywhere but that one function, and that function is never setting the values to 0.0, I'm not sure why they are reverting to the original value. Any ideas of why this could be happening?
My psychic debugging skills indicate some possibilities:
- You're shadowing the members when you assign them
float dX = small_float_value;
instead ofdX = small_float_value;
- You're working with different copies of
shapeObject
and the modified one gets thrown away by accident (or its copy constructor doesn't do the obvious thing). - The values only appear to still be zero in printing but are in fact the small float value you want.
- Somehow the small float value gets truncated to zero.
When adding or subtracting a small value try using cast by float like dx=dx+(float)0.001; Better try using double instead of float.Float has some precision problem.
Perhaps somewhere the small float value is being cast to an int before being added/subtracted so the resulting change is zero?
Need to see more code to do anything more than stab in the dark.
精彩评论