开发者

Is there a difference between int(floatvar) and (int)floatvar? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

int(floatvar)

(int)floatvar

Is there any difference between the two? Are there any preferences about wh开发者_StackOverflow中文版en to use which?


There is no difference between them. (int)floatvar is C way of doing the cast where as int(floatvar) is the C++ way (Although it is better to be explicit and use static_cast<>).


No, it's the same thing.

Anyway, for C++ cast static_cast is preferable.


The notation is a general one for any type, and the fact you can do it with int means it will work in templates.

template < typename T, typename U >
T makeTFromU( U u )
{
   return T( u );
}

Ok, that is a very simple case to show a point, but it works even when T is int and U is a type that can be converted to int.

An example in the standard library would be vector. If you use this constructor it constructs one element from the parameter and the others by copy-constructor from the first.

std::vector< int > v( 20, x );

thus it will probably internally call int(x) to create the first one to then copy into the 20 elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜