[英]what type of cast should I use here?
I have this code: 我有以下代码:
m_file.seekg(0, std::ios_base::end);
int fileSize = (int)(m_file.tellg());
m_file.seekg(0, std::ios_base::beg);
m_fileContent.resize(fileSize);
m_file.read(m_fileContent.data(), fileSize);
the idea is to read the content of a binary file into a vector. 这个想法是将二进制文件的内容读入向量。 This code is compiled and run well, but I am not sure this line is correct in a c++ environment?
这段代码已编译并运行良好,但是我不确定在C ++环境中此行是否正确?
int fileSize = (int)(m_file.tellg());
Am I using the correct cast? 我使用的演员正确吗? It is ac style cast and not a c++ one.
它是ac样式转换,而不是c ++。 I tried this cast but it generate compiler error:
我尝试了这种强制转换,但它会生成编译器错误:
int fileSize = reinterpret_cast<int>(m_file.tellg());
but I am getting this error: 但我收到此错误:
'reinterpret_cast' : cannot convert from 'std::fpos<_Mbstatet>' to 'int'
what is the best way to cast value types to each other? 相互转换值类型的最佳方法是什么? Should I use C style cast or C++ style cast?
我应该使用C样式转换还是C ++样式转换?
您根本不需要演员,而是使用
size_t fileSize = file.tellg();
You shouldn't be casting at all, but rather (assuming C++11) using auto
, ie: 您根本不应该进行强制转换,而是(假设C ++ 11)使用
auto
,即:
auto fileSize = m_file.tellg();
It will ensure that you don't use the wrong type and avoid implicit casts that may end up in losing info (like casting from a larger type to a smaller one). 它将确保您不会使用错误的类型,并避免可能导致信息丢失的隐式强制转换(例如从较大的类型转换为较小的类型)。 Plus you don't have to bother with the actual type (which can be cumbersome to type, and that you may get wrong).
另外,您不必担心实际的类型(键入可能很麻烦,而且可能会出错)。
Before C++11
I believe the correct thing to do is this: 在
C++11
之前,我相信正确的做法是:
std::fstream::pos_type fileSize = m_file.tellg();
If you have C++11
then you can do this: 如果您拥有
C++11
则可以执行以下操作:
auto fileSize = m_file.tellg();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.