首先我们以一个学生类为例,介绍继承的写法:(程序17.3.1) //student.h #include <iostream> using namespace std; class student//学生类作为父类 { public: student(char *n,int a,int h,int w);//带参数的构造函数 student();//不带参数的构造函数 void set(char *n,int a,int h,int w);//设置 char * sname(); int sage(); int sheight(); int sweight(); protected: char name[10];//姓名 int age;//年龄 int height;//身高 int weight;//体重 private: int test; }; char * student::sname() { return name; } int student::sage() { return age; } int student::sheight() { return height; } int student::sweight() { return weight; } void student::set(char *n,int a,int h,int w) { int i; for (i=0;n[i]!='/0';i++) { name[i]=n[i]; } name[i]='/0'; age=a; height=h; weight=w; return; } student::student(char *n,int a,int h,int w) { cout <<"Constructing a student with parameter..." <<endl; set(n,a,h,w); } student::student() { cout <<"Constructing a student without parameter..." <<endl; } //undergraduate.h #include "student.h" class Undergraduate:public student//本科生类作为子类,继承了学生类 { public: double score(); void setGPA(double g);//设置绩点 bool isAdult();//判断是否成年 protected: double GPA;//本科生绩点 }; double Undergraduate::score() { return GPA; } void Undergraduate::setGPA(double g) { GPA=g; return; } bool Undergraduate::isAdult() { return age>=18?true:false;//子类访问父类的保护成员数据 } //main.cpp #include <iostream> #include "undergraduate.h" using namespace std; int main() { Undergraduate s1;//新建一个本科生对象 s1.set("Tom",21,178,60); s1.setGPA(3.75); cout <<s1.sname() <<endl; cout <<s1.sage() <<endl; cout <<s1.sheight() <<endl; cout <<s1.sweight() <<endl; cout <<s1.score() <<endl; cout <<s1.isAdult() <<endl; return 0; }
运行结果: Constructing a student without parameter... Tom 21 178 60 3.75 1 在使用继承之前,我们必须保证父类是已经定义好的。如果父类是虚无的、没有被定义的,那么子类也就没什么好继承的了。定义一个子类的语法格式为: class 子类名:继承方式父类名; 根据程序17.3.1的运行结果,我们可以清楚地看到,学生类里面的公有和保护成员都已经被继承到本科生类。本科生类可以使用学生类的成员函数,也可以访问学生类的保护成员。而本科生类中定义的成员则是对学生类的补充,并且也能够被使用。