C++ (Qt)class A {};class B : public A {}; QDataStream & operator<< (QDataStream& stream, const A& a);QDataStream & operator>> (QDataStream& stream, A& a); QDataStream & operator<< (QDataStream& stream, const B& b);QDataStream & operator>> (QDataStream& stream, B& b); main{ A* b = new B(); QDataStream out(&file); out << *b; // Call QDataStream & operator<< (QDataStream& stream, A& a);}
C++ (Qt)#ifndef serialize_h#define serialize_h #include <QDataStream> class archive{public: enum rw_mode { read, write }; virtual ~archive() {}; virtual rw_mode mode() const = 0;}; class iarchive : public archive{public: rw_mode mode() const { return read; }}; class oarchive : public archive{public: rw_mode mode() const { return write; }}; class qds_iarchive : public iarchive{public: qds_iarchive( QIODevice *dev ) : m_stream( dev ) {} template<typename T> qds_iarchive &operator&( T &data ) { m_stream >> data; return *this; } private: QDataStream m_stream;}; class qds_oarchive : public iarchive{public: qds_oarchive( QIODevice *dev ) : m_stream( dev ) {} template<typename T> qds_oarchive &operator&( const T &data ) { m_stream << data; return *this; } private: QDataStream m_stream;}; #endif // serialize_h
C++ (Qt)#include <QCoreApplication>#include <QFile>#include <QDebug>#include "serialize.h" int main( int argc, char *argv[] ){ QCoreApplication app( argc, argv ); { QFile file( "test.dat" ); if( !file.open( QIODevice::WriteOnly ) ) { qWarning() << "File open error (write)"; return 1; } qint8 a = 0x10; qint16 b = 0x20; qint32 c = 0x30; qds_oarchive os( &file ); os & a; os & b; os & c; } { QFile file( "test.dat" ); if( !file.open( QIODevice::ReadOnly ) ) { qWarning() << "File open error (read)"; return 1; } qint8 a; qint16 b; qint32 c; qds_iarchive is( &file ); is & a; is & b; is & c; qDebug() << hex << a << b << c; } return 0;}
C++ (Qt) qDebug() << hex << a << b << c;