correctly fixing conversion and loss of data warnings?
I have a class called PointF
and it has a constructor that takes a Point
, and I keep getting "possible loss of data warnings". How can I show that my intention is in fact to make a float
value into an int
, among other tings? I tried static_cast
and (float)
but they did not fix the warning.
For example:
int curPos = ceil(float(newMouseY / font.getLineHeight())) ; //float to int
And
outputChars[0] = uc; //converting from size_t to char
开发者_开发问答
A cast should do the trick; that says "explicitly make this type into that type", which is generally pretty silly for a compiler to warn for:
int curPos = static_cast<int>(ceil(float(newMouseY / font.getLineHeight())));
Or:
outputChars[0] = static_cast<char>(uc);
Make sure the casts you tried were akin to that. You say "I tried ...(float)
" which leads me to believe you tried something like this:
int curPos = (float)(ceil(float(newMouseY / font.getLineHeight())));
Which does nothing. The type of the expression is already a float
, what would casting it to the same type do? You need to cast it to the destination type.
Keep in mind casts are generally to be avoided. In your first snippet, the cast is sensible because when you quantize something you necessarily need to drop information.
But your second cast is not. Why is uc
a size_t
in the first place? What happens when the cast does drop information? Is that really a good idea?
You need to cast the result of ceil
, preferably with a static_cast
.
you may have to use an explicit cast, i.e.
int curPos = int(ceil(...));
You must cast your variable to normally good way change type of her. And if you trying convert size_t
to char
, then you trying save 4 bytes
into 1 byte
, data lost is a normal thing in this way.
精彩评论