13.1.11 类文件的组织
信息隐藏对开发大型程序是非常有用的,它可以极大地保证程序质量。类的用户对于类中具体如何实现的并不感兴趣,它只需要了解类的说明(其中包含着类与外界的接口),这已足够使类的使用者能够使用类。一般,一个较大的类可以分为3个文件来存放:
将类的说明作为一个头文件来存放。
将类的实现单独组成一个文件,其中只含有关于类的成员函数定义,可单独编译,但因为没有入口点main()函数,不能运行。
将对类的使用放在一个文件中,其中包含一个main()函数。
【示例13-16】 student类的完整实现,它由3个文件组成,分别是类的头文件、类的实现文件,以及类的使用文件。
1.第1个文件
第1个文件student.h为头文件。代码如下:
- class student
- {
- private:
- int id;
- char* name;
- float chinese,english,math;
- public:
- student();
- student(int,char*,float,float,float);
- ~student();
- void setid(int);
- void setname(char *);
- void setscore(float,float,float);
- float sum();
- float average();
- }
分析:在此头文件中只需存放类的声明,其成员函数的实现不需在此列出。
2.第2个文件
第2个文件student.cpp,其中包含类的实现。代码如下:
- #include "student.h"
- #include "iostream.h"
- student::student()
- {
- id=0;
- name="##";
- chinese=english=math=0;
- cout<<"构造函数调用!"<<endl;
- }
- student::student(int n_id,char * n_name,float n_chinese,float n_english,
- float n_math)
- {
- id=n_id;
- name=n_name;
- chinese=n_chinese;
- english=n_english;
- math=n_math;
- cout<<"带参数构造函数调用!"<<endl;
- }
- void student::show()
- {
- cout<<"学号"<<setw(6)<<"姓名"<<setw(6)<<"语文"<<setw(6)<<"英语
- "<<setw(6)<<"数学"<<endl;
- cout<<id<<setw(6)<<name<<setw(6)<<chinese<<setw(6)<<english<<setw(6)
- <<math<<endl;
- }
- student::~student()
- {
- cout<<"析构函数!"<<endl;
- }
- void student::setid(int new_id)
- {
- id=new_id;
- }
- void student::setname(char * new_name)
- {
- name=new_name;
- }
- void setscore(float new_chinese, float new_enlisth, float new_math)
- {
- chinese=new_chinese;
- english=new_english;
- math=new_math;
- }
- float student::sum()
- {
- float sum;
- sum=chinese+english+math;
- return sum;
- }
- float student::average()
- {
- float average;
- average =(chinese+english+math)/3;
- return average;
- }
分析:在这个文件中要注意,它只包含类的成员函数,将要说明相应类的头文件包含进来,也要将使用系统库函数的头文件包含进来。
3.第3个文件
第3个文件是类的使用,其中应包含一个main()函数。代码如下:
- #include "student.h"
- #include "iostream.h"
- #include "iomanip.h"
- void main()
- {
- student s1(1,"Bob",80,90,85);
- s1.show();
- student s2;
- s2.show();
- student s3;
- s3=s1;
- s3.show();
- }
3个文件做好以后,就可利用集成开发环境建立工程文件,联合编译成可执行文件。
【责任编辑:
云霞 TEL:(010)68476606】