How can I know the size of qt data types in bytes; including QString objects if these data types were written on some QFile. I have to implement sizeOf()
function in the Student class as below; something like we sizeof(struct student)
in C.
Student class
#include<QtCore>
class Student
{
public:
QString name,fname;
quint8 age,weight,clss;
Student(){
}
/*the following function should return the size of this object in bytes;
I will use QDataStream & operator<<(QDataStream &out, Student &f)
function to write data to a QFile */
qint16 sizeOf()
{
// needs implementation;
}
};
QDataStream & operator<<(QDataStream &out, Student &f)
{
out<<f.name<<f.fname<<f.age<<f.weight<<f.clss<<f.next;
return out;
}
QDataStream & operator>>(QDataStream &in, Student &f)
{
in>>f.name>>f.fname>>f.age>>f.weight>>f.clss>>f.next;
return in;
}
I know that data can be read with QDataStream & operator>>(QDataStream &in, Student &f)
; but I want to know size also for some other cases.
This does not give me a valid size on file. It seems Qt adds some extra bits while serializing; possibly for endian-ness independency on different platforms. Actual size is always more than returned by sizeOf()
function
qint16 sizeOf()
{
qint16 size=0;
size+=sizeof(quint8)*3; // size of age, weight and clss
//variables all have type quint8
size+=name.size()*16; // number of characters in string
// multiply with 16 bit QChar
size+=fname.size()*16;
return size;
}
I am using QFile, QDataStream api. Qt version 4.8 on Windows 8.