a/c cho em hỏi, sao em đọc ghi file bài này bằng kiểu nhị phân thì không được mà em đọc kiểu text lại được, em nghe đồn là liên quan đến con trỏ ạ. Còn phần nạp chồng toán tử + để cộng 2 danh sách sao lúc truyền tham chiếu phải truyền bằng tham biến, nếu truyền tham trị thì không được ạ.
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
class sinhvien{
private:
long ma;
char ten[8];
public:
void set_ma(int x){ ma=x;
}
long get_ma(){ return ma;
}
void set_ten(char x[]){ strcpy(ten,x);
}
char *get_ten(){ return ten;
}
void nhap(){
cin.getline(ten,8);
cin>>ma; cin.ignore();
}
void xuat(){
cout<<ten<<" "<<ma<<endl;
}
};
struct node{
sinhvien info;
node *next;
};
node *khoitaonode(sinhvien x){
node *p=new node;
p->info.set_ma(x.get_ma());
p->info.set_ten(x.get_ten());
p->next=NULL;
return p;
}
class danhsach{
private:
node *pfirst;
node *plast;
public:
friend danhsach operator+(danhsach &a, danhsach &b);
danhsach(){
pfirst=NULL;
plast=NULL;
}
void themcuoi( sinhvien x){
node *p= khoitaonode(x);
if(pfirst==NULL) pfirst=plast=p;
else {
plast->next=p;
plast=p;
}
}
void ghitep(){
ofstream file("4.dat",ios::binary);
file.write(reinterpret_cast <char*> (this),sizeof(danhsach));
file.close();
}
void doctep(){
ifstream file("4.dat",ios::binary);
file.read(reinterpret_cast <char*> (this),sizeof(danhsach));
file.close();
}
~danhsach(){
ghitep();
for(node *k=pfirst; k!=NULL;k=pfirst){
pfirst=k->next;
delete k;
}
}
};
danhsach operator+(danhsach &a, danhsach &b){
danhsach c; node *k;
for(k=a.pfirst; k!=NULL;k=k->next){
c.themcuoi(k->info);
}
for(k=b.pfirst; k!=NULL;k=k->next){
c.themcuoi(k->info);
}
return c;
}
main(){
danhsach a,b; sinhvien x; node *p;
for(int i=0;i<4;i++){
x.nhap();
p=khoitaonode(x);
a.themcuoi(p->info);
}
a.ghitep();
b.doctep();
b.xemmh();
}