【聚杰网C++】C++的iostream标准库介绍
为了巩固学习,下面我们以fstream对象输出为例做一个练习。
代码如下:
| //程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include<iostream> #include<fstream> usingnamespacestd; classTest { public: Test(intage=0,char*name="/0") { Test::age=age; strcpy(Test::name,name); } voidoutmembers(ostream&out) { out<<"Age:"<<age<<endl<<"Name:"<<this->name<<endl; } friendostream&operator<<(ostream&,Test&); protected: intage; charname[50]; }; ostream&operator<<(ostream&out,Test&temp) { temp.outmembers(out); returnout; } intmain() { Testa(24,"管宁"); ofstreammyfile("c://1.txt",ios::out,0); if(myfile.rdstate()==ios_base::goodbit) { myfile<<a; cout<<"文件创建成功,写入正常!"<<endl; } if(myfile.rdstate()==ios_base::badbit) { cout<<"文件创建失败,磁盘错误!"<<endl; } system("pause"); } |
对于左移运算符重载函数来说,由于不推荐使用成员方式,那么使用非成员方式在类有多重继承的情况下,就不能使用虚函数进行左移运算符重载的区分,为了达到能够区分显示的目的,给每个类分别添加不同的虚函数是必要的。
示例代码如下:
| //程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include<iostream> #include<fstream> usingnamespacestd; classStudent { public: Student(intage=0,char*name="/0") { Student::age=age; strcpy(Student::name,name); } virtualvoidoutmembers(ostream&out)=0; friendostream&operator<<(ostream&,Student&); protected: intage; charname[50]; }; ostream&operator<<(ostream&out,Student&temp) { temp.outmembers(out); returnout; } classAcademician:publicStudent { public: Academician(intage=0,char*name="/0",char*speciality="/0"):Student(age,name) { strcpy(Academician::speciality,speciality); } virtualvoidoutmembers(ostream&out) { out<<"Age:"<<age<<endl<<"Name:"<<name<<endl<< "speciality:"<<speciality<<endl; } protected: charspeciality[80]; }; classGraduateStudent:publicAcademician { public: GraduateStudent(intage=0,char*name="/0",char*speciality="/0", char*investigate="/0"):Academician(age,name,speciality) { strcpy(GraduateStudent::investigate,investigate); } virtualvoidoutmembers(ostream&out) { out<<"Age:"<<age<<endl<<"Name:"<<name<<endl<< "speciality:"<<speciality<<endl<<"investigate:"<<investigate<<endl; } protected: charinvestigate[100]; }; intmain() { Academiciana(24,"管宁","ComputerScience"); cout<<a; GraduateStudentb(24,"严燕玲","ComputerScience","GISSystem"); cout<<b; system("pause"); } |
在上面的代码中为了能够区分输出a对象与b对象,我们用虚函数的方式重载了继承类Academician与多重继承类GraduateStudent的outmembers成员函数,由于ostream& operator <<(ostream& out,Student &temp) 运算符重载函数是Student基类的,Student &temp参数通过虚函数的定义可以适应不同派生类对象,所以在其内部调用temp.outmembers(out); 系统可识别不同继类的outmembers()成员函数。





