为了巩固学习,下面我们以fstream对象输出为例做一个练习。
代码如下:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 #include <iostream> #include <fstream> using namespace std; class Test { public: Test(int age = 0,char *name = "\0") { Test::age = age; strcpy(Test::name,name); } void outmembers(ostream &out) { out<<"Age:"<<age<<endl<<"Name:"<<this->name<<endl; } friend ostream& operator <<(ostream& ,Test&); protected: int age; char name[50]; }; ostream& operator <<(ostream& out,Test &temp) { temp.outmembers(out); return out; } int main() { Test a(24,"管宁"); ofstream myfile("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> using namespace std; class Student { public: Student(int age = 0,char *name = "\0") { Student::age = age; strcpy(Student::name,name); } virtual void outmembers(ostream &out) = 0; friend ostream& operator <<(ostream& ,Student&); protected: int age; char name[50]; }; ostream& operator <<(ostream& out,Student &temp) { temp.outmembers(out); return out; } class Academician:public Student { public: Academician(int age = 0,char *name = "\0",char *speciality="\0"):Student(age,name) { strcpy(Academician::speciality,speciality); } virtual void outmembers(ostream &out) { out<<"Age:"<<age<<endl<<"Name:"<<name<<endl<< "speciality:"<<speciality<<endl; } protected: char speciality[80]; }; class GraduateStudent:public Academician { public: GraduateStudent(int age = 0,char *name = "\0",char *speciality="\0", char *investigate="\0"):Academician(age,name,speciality) { strcpy(GraduateStudent::investigate,investigate); } virtual void outmembers(ostream &out) { out<<"Age:"<<age<<endl<<"Name:"<<name<<endl<< "speciality:"<<speciality<<endl<<"investigate:"<<investigate<<endl; } protected: char investigate[100]; }; int main() { Academician a(24,"管宁","Computer Science"); cout<<a; GraduateStudent b(24,"严燕玲","Computer Science","GIS System"); cout<<b; system("pause"); }
在上面的代码中为了能够区分输出a对象与b对象,我们用虚函数的方式重载了继承类Academician与多重继承类GraduateStudent的outmembers成员函数,由于ostream& operator <<(ostream& out,Student &temp) 运算符重载函数是Student基类的,Student &temp参数通过虚函数的定义可以适应不同派生类对象,所以在其内部调用temp.outmembers(out); 系统可识别不同继类的outmembers()成员函数。 |