C++

文件

定义一个Dog类,包括体重和年龄两个数据成员及其成员函数,声明一个实例dog1,体重5,年龄10,使用I/O流把dog1的状态写入磁盘文件。再声明一个实例dog2,通过读取文件dog1的状态赋给dog2。

#include<iostream>

#include<fstream>

using namespace std;

class Dog

{

public:

       int getdoga(){return a;}   

       int getdogw(){return w;}

void setdog(int x,int y)

{

a=x;w=y;

}

private:

       int a,w;

};

int main()

{

int v1,v2;

Dog dog1;

dog1.setdog(10,5);

ofstream

outFile("outfile.txt",ios::out);

outFile<<dog1.getdoga()<<" "<<dog1.getdogw();

outFile.close();

Dog dog2;

ifstream

inFile("outfile.txt",ios::in);

inFile>>v1;inFile.seekg(1,ios::cur);inFile>>v2;

dog2.setdog(v1,v2);

outFile.close();

cout<<"dog1's age:"<<dog1.getdoga()<<endl;

cout<<"dog1's weight:"<<dog1.getdogw()<<endl;

cout<<"dog2's age:"<<dog2.getdoga()<<endl;

cout<<"dog2's weight:"<<dog1.getdogw()<<endl;

}

posted @ 2023-05-18 18:37  涨涨涨张  阅读(38)  评论(0编辑  收藏  举报