我应该在这里使用什么类型的演员?

时间:2022-04-06 05:22:04

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 a c style cast and not a c++ one. I tried this cast but it generate compiler error:

我使用的是正确的演员吗?它是一个c风格的演员而不是c ++演员。我尝试了这个演员,但它产生了编译器错误:

 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 ++样式转换?

3 个解决方案

#1


3  

You shouldn't be casting at all, but rather (assuming C++11) using auto, i.e.:

你根本不应该投,而是(假设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).

它将确保您不使用错误的类型并避免可能最终丢失信息的隐式转换(例如从较大类型转换为较小类型)。另外,您不必为实际类型而烦恼(打字可能很麻烦,而且您可能会出错)。

#2


3  

You don't want a cast at all, instead use

您根本不需要演员,而是使用

size_t fileSize = file.tellg();

#3


0  

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();

#1


3  

You shouldn't be casting at all, but rather (assuming C++11) using auto, i.e.:

你根本不应该投,而是(假设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).

它将确保您不使用错误的类型并避免可能最终丢失信息的隐式转换(例如从较大类型转换为较小类型)。另外,您不必为实际类型而烦恼(打字可能很麻烦,而且您可能会出错)。

#2


3  

You don't want a cast at all, instead use

您根本不需要演员,而是使用

size_t fileSize = file.tellg();

#3


0  

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();