不想写。我想睡觉。
向生活低头。我写。QWQ
面向对象的程序设计的重要特性之一就是代码重用,可以提高程序开发效率。
class 派生类名:继承方式 基类名 { 派生类成员的声明 } ;
继承方式有三种 private public protected.默认情况下是private。
类的继承方式决定了派生类成员以及类外对象对从基类继承来的成员的访问权限。
class Person { public: Person(const char *Name,int Age,char Sex); char* getName(); int getAge(); char GetSex(); void Display(); private: char name[11]; char sex; int age; }; class Student::public Person { public: Student(char*pName,int Age,char Sex,char *pId,float score):Person(pName,Age,Sex); char *GetId(char *pId); float GetScore(); void Display(); private: char sid[9]; float score; } ; class Teacher:public Person { public: Teacher(char *pName,int Age,char Sex,char *pId,char *pprof,float Salary): Person(pName,Age,Sex); char *GetId(char *pId); char *Getprof(char *pprof); float GetSalary(); void Display(); private: char id[9]; char prof[12]; float salary; };
基类的构造函数和析构函数派生类不继承
派生类可以通过继承方式来控制派生类类内和类外对基类成员的访问。
尽管派生类继承了基类的全部成员。但其对基类成员的访问却受到基类成员自身访问权限和派生类继承方式的共同制约。
①基类的私有成员在派生类中以及派生类外均不可访问,只能由基类的成员函数访问。
②公用继承。基类中的公用成员和保护成员在派生类中访问属性不变,派生类外仅能访问公用成员。
③保护继承。基类中的公用成员和保护成员在派生类中均为保护成员,在派生类外不能访问从基类继承的任何成员。
④私有继承。基类中的公用成员和保护成员在派生类中均为私有成员,派生类外不能访问基类继承的任何成员。
(一)公用继承
#include<iostream> #include<cstring> using namespace std; class Person { public: Person(const char *Name,int Age,char Sex) { strcpy(name,Name); age=Age;sex=Sex; } char *GetName() { return name; } int GetAge(){return age;} char GetSex(){return sex;} void Display() { cout<<"name:"<<name<<‘\t‘; cout<<"age:"<<age<<‘\t‘; cout<<"sex:"<<sex<<endl; } private: char name[11]; char sex; protected: int age; }; class Student:public Person { public://调用基类的构造函数初始化基类的数据成员。 Student(char *pName,int Age,char Sex,char *pId,float Score):Person(pName,Age,Sex) { strcpy(id,pId); score=Score; } char *GetId(){ return id;} float GetScore() {return score;} void Display() { cout<<"id:"<<id<<‘\t‘; cout<<"age:"<<age<<‘\t‘; cout<<"score:"<<score<<endl; } private: char id[9]; float score; }; int main() { char name[11]; cout<<"Enter a person‘s name:"; cin>>name; Person p1(name,29,‘m‘); p1.Display(); char pId[9]; cout<<"Enter a student‘s name:"; cin>>name; Student s1(name,19,‘f‘,"03410101",95); cout<<"name:"<<s1.GetName()<<‘\t‘; cout<<"id:"<<s1.GetId()<<‘\t‘; cout<<"age:"<<s1.GetAge()<<‘\t‘; cout<<"sex:"<<s1.GetSex()<<‘\t‘; cout<<"score:"<<s1.GetScore()<<endl; return 0; }
原文:https://www.cnblogs.com/zzyh/p/11922936.html