谢谢你给的回答啊,我还有一个问题想请教一下

2024-12-30 18:39:24
推荐回答(1个)
回答1:

这个有点难度,我写了一个,可以参考:
enum SHAPE_CODE
{
RECTANGLE,
CIRCLE,
};

class Element
{
public:
virtual int getShape() = 0;
virtual void read( FILE* fp ) = 0;
virtual void write( FILE* fp ) = 0;
};

class CRectangle : public Element
{
public:
virtual int getShape() { return RECTANGLE; };

virtual void read( FILE* fp )
{
fread( &p1, sizeof( p1 ), 1, fp );
fread( &p2, sizeof( p2 ), 1, fp );
}

virtual void write( FILE* fp )
{
fwrite( &p1, sizeof( p1 ), 1, fp );
fwrite( &p2, sizeof( p2 ), 1, fp );
}

private:
POINT p1;
POINT p2;
};

class CCircle : public Element
{
public:
virtual int getShape() { return CIRCLE; };

virtual void read( FILE* fp )
{
fread( ¢er, sizeof( center ), 1, fp );
fread( &r, sizeof( r ), 1, fp );
}

virtual void write( FILE* fp )
{
fwrite( ¢er, sizeof( center ), 1, fp );
fwrite( &r, sizeof( r ), 1, fp );
}

private:
POINT center;
int r ;
};

void readIt()
{
FILE *fp = fopen( "test", "rb" );
int count;
fread( &count, sizeof( count ), 1, fp );
Element **elm = new Element *[ count ];
for ( int i = 0; i < count; ++i )
{
int shape;
fread( &shape, sizeof( shape ), 1, fp );
switch ( shape )
{
case RECTANGLE:
elm[ i ] = new CRectangle;
break;
case CIRCLE:
elm[ i ] = new CCircle;
break;
}
elm[ i ]->read( fp );
}

fclose( fp );
}

int main()
{
CCircle c;
CRectangle r;

Element *elm[] = { &c, &r };

FILE *fp = fopen( "test", "wb" );
int count = _countof( elm );
fwrite( &count, sizeof( count ), 1, fp );
for ( int i = 0; i < count; ++i )
{
int shape = elm[ i ]->getShape();
fwrite( &shape, sizeof( shape ), 1, fp );
elm[ i ]->write( fp );
}

fclose( fp );

readIt();
}