【发布时间】:2020-05-14 15:57:54
【问题描述】:
这是我编译时出现警告的代码的一部分,我无法理解如何避免算术溢出问题
void read(int pn) //read person number pn
{
ifstream infile;
infile.open("data.txt", ios::binary);
infile.seekg(pn * sizeof(makers)); // this is the line I get warning
infile.read((char*)this, sizeof(*this));
}
我得到的警告:
Arithmetic overflow: Using operator '*' on a 4 byte value and then
casting the result to a 8 byte value. Cast the value to the wider
type before calling operator '*' to avoid overflow (io.2).
【问题讨论】:
-
@HANA 你是说将
pn转换为std::size_t没有解决你的问题吗?infile.seekg(static_cast<std::size_t>(pn) * sizeof(makeres));? -
您需要比“它不起作用”更具体。当您尝试这些解决方案时,结果如何?错误信息是相同还是不同?
-
错误信息指向哪一行?你真的向我们展示了正确的路线吗?
-
现在,你看到了吗? @JohnFilleau
-
这并没有解决问题,但是使用
read调用来爆破现有对象中的位将在除了最狭窄的情况之外的所有情况下导致麻烦。
标签: c++ function oop math overflow