保存和检索具有 const 成员变量的对象的内容(到磁盘文件或从磁盘文件)的方法是什么?
或者更具体地说,const 成员要求在对象创建时进行初始化。因此,内容的检索必须发生在初始化器之前(构造函数的 { } 之前)。如果我们不介意封装,我们可以检索并创建带参数的对象。如何通过保持数据隐藏来完成所有事情?
编译器:C++ 14 或更高版本。
实例化对象,填充内容并存储以供下一个上下文使用。
{ //CODE BLOCK 1 : making of content and saving to a diskfile
Abcd abcd(65535,256,25);
//some operations on abcd
//save to disk
QFile abcdFile("abcd.lion");
abcdFile.open(QFile::WriteOnly);
abcd.serialize(abcdFile);
abcdFile.close();
}
从文件中获取后使用相同的对象。
{ //CODE BLOCK 2 : loading from file and continue in another context
QFile abcdFile("abcd.lion");
abcdFile.open(QFile::ReadOnly);
Abcd abcdNew(abcdFile);
abcdFile.close();
if(!abcdNew.isHealthy())
printf("abcd from hdd is NOT Healthy :(\n");
else
{
//doTheJob(abcdNew);
}
}
类(class)。
#include <QFile>
class Abcd
{
const bool _healthy;//true if properly initialized
//IMPORTANT: _healthy has to be the first member in the class.
//this is to execute its initializer list first
protected:
const long _rX;
const long _rY;
long _count;
public:
Abcd(const long refX,
const long refY,
const long count) :
_healthy(true),
_rX(refX), _rY(refY),
_count(count)
{
}
Abcd(QFile &src) :
_healthy(deserialize(src)),
//Hack. Actually the initialization happened by this statement.
//just keeping the below statements for the sake of syntactical correctness. :(
_rX(_rX), _rY(_rY)
//,_count(count)
{
}
virtual
~Abcd()
{
}
inline
bool isHealthy()
{
return _healthy;
}
bool serialize(QFile &dest)
{
if(dest.write((char *)&_rY,sizeof(_rY))!=sizeof(_rY)) return false;
if(dest.write((char *)&_rX,sizeof(_rX))!=sizeof(_rX)) return false;
if(dest.write((char *)&_count,sizeof(_count))!=sizeof(_count)) return false;
return true;
}
private:
bool deserialize(QFile &src)
{
if(src.read((char *)&_rY,sizeof(_rY))!=sizeof(_rY)) return false;
if(src.read((char *)&_rX,sizeof(_rX))!=sizeof(_rX)) return false;
if(src.read((char *)&_count,sizeof(_count))!=sizeof(_count)) return false;
return true;
}
};
请提出更好的方法。为此,我在类(class)声明中引入了一位“健康”状态的成员作为第一个成员。同样在反序列化中,我通过将 const 变量强制转换为 char * 指针来欺骗编译器。
最佳答案
我的建议是使用类的static
成员函数从磁盘检索文件的内容,并在成功检索内容后构造一个对象。
而不是:
Abcd(QFile &src) :
使用
static Abcd deserialize(QFile& src);
并将其实现为:
Abcd Abcd::deserialize(QFile& src)
{
long rX;
long rY;
long count;
if(src.read((char *)&rY, sizeof(rY)) != sizeof(rY)) throw false;
if(src.read((char *)&rX, sizeof(rX)) != sizeof(rX)) throw false;
if(src.read((char *)&count, sizeof(count)) != sizeof(count)) throw false;
return Abcd(rX, rY, count):
}
PS 奇怪的是,你先保存了_rY
,然后又保存了_rX
。没有什么不对,只是有点奇怪。
关于c++ - 如何从文件加载const变量的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54820238/