c++中的类型转换结构

Type casting struct in C++

本文关键字:结构 类型转换 c++      更新时间:2023-10-16

在c++中我面临着一些困难!我想知道这些c语句在c++中的等价是什么?

struct stat sb; // this is struct, will be same in c++
printf("I-NODE NUMBER: %ldn", (long) sb.st_ino); // this is C statement
// c++ statement of above statement
cout<<" Inode number: "<< (long) sb.st_ino; // is this the correct way?
// or this one
cout<<" Inode number: "<< (long) (long) sb.st_ino; // is this the correct way?

虽然c风格的强制转换可以在c++中工作,但使用C++风格的强制转换被认为是更好的风格。那就是在你列出的情况下使用static_cast。像这样:

cout<<" Inode number: "<< static_cast<long>(sb.st_ino);

同样,在最后一个例子中,将表达式两次强制转换为同一类型是没有意义的。如果您要写的是转换为long long,请使用:

cout<<" Inode number: "<< static_cast<long long>(sb.st_ino);

还要查找dynamic_cast, const_cast, reinterpret_cast(最后两个应该尽可能避免使用)。

在c++中,您可能只需要执行以下操作。完全不需要强制转换。

std::cout << " Inode number: " << sb.st_ino;