程序设计与算法(三)C++面向对象程序设计 第五周 相关笔记
一、
继承与派生的基本概念


#include<bits/stdc++.h> using namespace std; class Student{ private: string name; char sex; int height,weight; public: Student(string _name,char _sex,int _h,int _w):name(_name),sex(_sex),height(_h),weight(_w){ } void get_info(){ cout<<name<<'\n'<<sex<<'\n'<<height<<" "<<weight<<endl; } void set_h(int h){ height = h; } void set_w(int w){ weight = w; } }; class CollegeStudent:public Student{ private: bool is_baoyan; int grades; public: CollegeStudent(string _name,char _sex,int _h,int _w,int g,bool b) :Student(_name,_sex,_h,_w),grades(g),is_baoyan(b){ } void get_info(){ Student::get_info(); cout<<grades<<'\n'<<is_baoyan<<'\n'; } void set_g(int g){ grades = g; } void set_b(bool b){ is_baoyan = b; } }; int main(){ CollegeStudent s("Bruce",'M',180,65,100,1); s.get_info(); s.set_g(233); s.get_info(); s.set_h(123); s.get_info(); s.set_w(12424); s.get_info(); s.set_b(0); s.get_info(); return 0; }
想改变基类的成员变量可以用基类的构造函数或者用set_info函数
二、
继承关系和复合关系
继承关系:从属关系 B继承A -> B是A
复合关系:B有A



三、
类的保护成员

protected = private + 派生类的成员函数可访问当前对象基类的保护成员
四、
派生类的构造函数



构造函数顺序:
先基类->成员对象类->派生类构造函数
(为了不出错,每个构造的时候都可以访问基类或成员对象)
析构函数顺序:相反 :基类最后被析构
五、public继承的复制兼容规则

及可以用基类的操作它的派生类
六、直接基类间接基类
可套娃,自动向上延续

浙公网安备 33010602011771号