what C++ casting operator is equivalent to (MyStructType){1,2,3}?
Is there an C++ casting operator (or combination t开发者_高级运维hereof) equivalent to the old-style cast below:
struct MyStruct {
int i;
int j;
int k;
};
void do_something_with_mystruct( MyStruct ms ) {
...
};
int main( int argc, char** argv ) {
do_something_with_mystruct( (MyStruct){1,2,3} );
};
The construct
(MyStruct) {1,2,3}
is not actually a cast! It's an ISO C99 "compound literal". There is no equivalent using any of the C++ *_cast<>
operators, because C++ (even C++0x) does not include this construct. Some compilers implement it as an extension to C++, but you still have to write it this way. See for instance http://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Compound-Literals.html.
The equivalent to the C style cast is:
reinterpret_cast<ToType>(fromType);
It does a blind conversion of the bit pattern. Unsafe in most cases, useful when you need it.
精彩评论