我正在研究 cpp 文件中的随机访问。我遇到了 reinterpret_cast 运算符。它允许您将指针从一种类型转换为另一种类型,即使这些类型之间没有任何关联。但是,据说这被认为是危险的,可能会产生意外结果和程序崩溃。我想了解为什么以及如何?
我写的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("example.txt", ios::out);
if (!file)
{
cerr << "Failed to open file." << endl;
return 1;
}
file.seekp(4 * sizeof(int), ios::beg);
int newValue = 50;
file.write(reinterpret_cast<const char *>(&newValue), sizeof(int));
file.close();
return 0;
}