QDataStream用二進位寫自定義類數據?

QDataStream 可以寫字元串,uint等等基本的數據類型,或許還支持其他的類,但是都是qt庫中封裝的類,而對於自己的類對象數據,該怎麼寫呢?我直接QDataStream stream(file);

Person per("xx","yy");//Person(char* name,char* sex);

stream &<&< (char*)per;

這樣的方式 可以寫數據,但是好像只寫了一部分,我read的時候,只能讀出name的那段數據


可以參考一下Qt中複雜類型的代碼。

http://doc.qt.io/qt-5/datastreamformat.html

https://github.com/qtproject/qtbase/blob/5.5/src/corelib/tools/qeasingcurve.cpp#L1432-L1493

#ifndef QT_NO_DATASTREAM
QDataStream operator&<&<(QDataStream stream, const QEasingCurve easing) { stream &<&< quint8(easing.d_ptr-&>type);
stream &<&< quint64(quintptr(easing.d_ptr-&>func));

bool hasConfig = easing.d_ptr-&>config;
stream &<&< hasConfig; if (hasConfig) { stream &<&< easing.d_ptr-&>config-&>_p;
stream &<&< easing.d_ptr-&>config-&>_a;
stream &<&< easing.d_ptr-&>config-&>_o;
}
return stream;
}

QDataStream operator&>&>(QDataStream stream, QEasingCurve easing)
{
QEasingCurve::Type type;
quint8 int_type;
stream &>&> int_type;
type = static_cast&(int_type);
easing.setType(type);

quint64 ptr_func;
stream &>&> ptr_func;
easing.d_ptr-&>func = QEasingCurve::EasingFunction(quintptr(ptr_func));

bool hasConfig;
stream &>&> hasConfig;
delete easing.d_ptr-&>config;
easing.d_ptr-&>config = Q_NULLPTR;
if (hasConfig) {
QEasingCurveFunction *config = curveToFunctionObject(type);
stream &>&> config-&>_p;
stream &>&> config-&>_a;
stream &>&> config-&>_o;
easing.d_ptr-&>config = config;
}
return stream;
}
#endif // QT_NO_DATASTREAM


嗯,再csdn博客中找到一篇博文可以成功解決問題,

轉自:QDataStream傳遞自定義的數據類型

#ifndef MYDATASTREAM_H

#define MYDATASTREAM_H

#include &

struct UserInfor{

QString id;

QString state;

QString ip;

QString port;

QString nickName;

QByteArray headPhoto;

QString discription;

};

inline QDataStream operator&<&<(QDataStream out, const UserInfor userInfor)

{

out&<& userInfor.nickName&<& return out;

}

inline QDataStream operator&>&>(QDataStream in,UserInfor userInfor)

{

in&>&>userInfor.id&>&>userInfor.state&>&>userInfor.ip&>&>userInfor.port&>&>userInfor.nickName

&>&>userInfor.headPhoto&>&>userInfor.discription;

return in;

}

#endif // MYDATASTREAM_H


推薦閱讀:

MFC,QT,WPF,.NET比WIN32 API做界面有哪些優勢?

TAG:編程 | QtC開發框架 | C |