class 派生类名:public 基类名 { };例子
class CStudent { private: string sName; int nAge; public: bool IsThreeGood() { }; void SetName( const string & name ) { sName = name; } //...... }; class CUndergraduateStudent: public CStudent { private: int nDepartment; public: bool IsThreeGood() { ...... }; //覆盖 bool CanBaoYan() { .... }; }; // 派生类的写法是:类名: public 基类名覆盖:派生类中的成员函数和基类中的完全一样,但行为可能需要不一样,所以在派生类中对函数的行为重新编写。这里感觉应该是隐藏,而不是覆盖,至于重载、覆盖、隐藏等的区别,后面有时间专门写个博客总结下。
class CBase { int v1,v2; }; class CDerived:public CBase { int v3; };
#include <iostream> #include <string> using namespace std; class CStudent { private: string name; string id; //学号 char gender; //性别,'F'代表女,'M'代表男 int age; public: void PrintInfo(); void SetInfo( const string & name_,const string & id_,int age_, char gender_ ); string GetName() { return name; } }; class CUndergraduateStudent:public CStudent {//本科生类,继承了CStudent类 private: string department; //学生所属的系的名称 public: void QualifiedForBaoyan() { //给予保研资格 cout << “qualified for baoyan” << endl; } void PrintInfo() { CStudent::PrintInfo(); //调用基类的PrintInfo cout << “Department:” << department <<endl; } void SetInfo( const string & name_,const string & id_,int age_,char gender_ ,const string & department_) { CStudent::SetInfo(name_,id_,age_,gender_); //调用基类的SetInfo department = department_; } }; void CStudent::PrintInfo() { cout << "Name:" << name << endl; cout << "ID:" << id << endl; cout << "Age:" << age << endl; cout << "Gender:" << gender << endl; } void CStudent::SetInfo( const string & name_,const string & id_,int age_,char gender_ ) { name = name_; id = id_; age = age_; gender = gender_; } int main() { CUndergraduateStudent s2; s2.SetInfo(“Harry Potter ”, “118829212”,19,‘M’,“Computer Science”); cout << s2.GetName() << “ ” ; s2.QualifiedForBaoyan (); s2.PrintInfo (); return 0; } 输出结果: Harry Potter qualified for baoyan Name:Harry Potter ID:118829212 Age:19 Gender:M Department:Computer Science像在派生类的PrintInfo函数中那样,先调用了基类里面的同名成员函数,完成跟基类有关的事。然后再写一些代码,完成跟派生有关的事。这种做法实际上是特别常见的。
原文地址:http://blog.csdn.net/buxizhizhou530/article/details/45192097