#include<iostream> using namespace std; //基類 Pelple class People{ public: void setname(char *name); void setage(int age); char *getname(); int getage(); private: char *m_name; int m_age; }; void People::setname(char *name){ m_name = name; } void People::setage(int age){ m_age = age; } char* People::getname(){ return m_name; } int People::getage(){ return m_age;} //派生類 Student class Student: public People{ public: void setscore(float score); float getscore(); private: float m_score; }; void Student::setscore(float score){ m_score = score; } float Student::getscore(){ return m_score; } int main(){ Student stu; stu.setname("小明"); stu.setage(16); stu.setscore(95.5f); cout<<stu.getname()<<"的年齡是 "<<stu.getage()<<",成績是 "<<stu.getscore()<<endl; return 0; }運行結果:
class Student: public People
這就是聲明派生類的語法。class 後面的“Student”是新聲明的派生類,冒號後面的“People”是已經存在的基類。在“People”之前有一關鍵宇 public,用來表示是公有繼承。
class 派生類名:[繼承方式] 基類名{
派生類新增加的成員
};