1.用友元的一个输出
代码如下:
#include <iostream>
#include<fstream>
using namespace std;
class Stu {
string name;
int age;
public:
Stu(string n, int a) {name = n; age = a;}
friend ostream&operator<<(ostream& out, Stu s) {
out << s.name << " " << s.age << endl; return out;
}
};
int main() {
Stu s1("zhang", 20);
int a = 3;
cout << s1;
return 0;}
2.自己新建一个txt文件,然后对它进行输入和输出
代码如下:
#include <iostream>
#include<fstream>
using namespace std;
class Stu {
string name;
int age;
public:
Stu(string n = " ", int a = 0) { name = n; age = a; }
void show() { cout << name << " " << age << endl; }
friend void WriteFile(ofstream& out, Stu& s) { out << s.name << " " << s.age << endl;}
friend void ReadFile (ifstream& in , Stu& s) { in >> s.name >> s.age ; }
};
int main() {
Stu s[3] = { Stu("zhang",20),Stu("lisi",21),Stu("wang",22) };
ofstream out("D:\\S.txt", ios::out);//需要新建一个txt文件并写上文件名
if (!out) { cout << "error"; }
for (int i = 0; i < 3; i++)
WriteFile(out, s[i]);
out.close();
ifstream in("D:\\S.txt", ios::in);
Stu st;
for (int i = 0; i < 3; i++) {
ReadFile(in, s[i]);
in.close();
}
}