• C++课程小结 继承与派生


    单继承与多重继承的区别

    单继承:一个子类(派生类)只有一个父类(只由一个基类派生而成)
    多继承:一个子类(派生类)有多个父类(由多个基类派生而成)
    

    派生类的构成

    (1) 从基类继承过来的成员(包括数据成员和成员函数)
    (2) 在派生类里面新增的成员(包括数据成员和成员函数)
    
    根据继承方式的不同来调整从基类继承过来成员的属性(public,protected,private。最经常使用protected)
    派生类的构造函数需要自己定义和声明,不能从基类继承过来,定义的时候需要调用其父类的构造函数。
    

    基类成员的接受

    注意点:
    1.在派生类里可以定义同名数据成员进行覆盖。
    2.不接受构造析构函数。
    3.通过继承方式改变访问属性。
    

    基类不能访问其派生类的新增成员。对于派生类访问基类的成员,如何确定基类成员在派生类中的访问属性?
    1.基类成员声明时的访问属性
    2.继承方式

    public 继承下,派生类赋值给父类

    1.不能用基类对象对其派生类对象赋值。
    2.同一基类的不同派生类的对象之间不能赋值。
    3.派生类对象可以向其基类的对象及其引用进行赋值。

    #include <iostream>
    #include <cstdlib>
    #include <string>
    using namespace std;
    
    class Student
    {
    	private:
    		string name;
    		int age;
    	public:
    		Student(string s = "", int a = 0): age(a){name = s;};
    		void print();
    };
    
    void Student::print()
    {
    	cout << name << " " << age << endl;
    }
    
    class UnderGraduate : public Student
    {
    	private:
    		int num;
    		int score;
    	public:
    		UnderGraduate(string s = "", int age = 0, int i_num = 0, int i_score = 0):
    		Student(s, age), num(i_num), score(i_score){};
    		void display();
    };
    
    void UnderGraduate::display()
    {
    	print();
    	cout << num << " " << score << endl;
    }
    
    int main()
    {
    	UnderGraduate A("LiMing", 20, 10005, 100);
    	
    	A.display();
    	
    	Student B = A;
    	
    	B.print();
    	
    	return 0;
    }
    

    4.如果函数参数是基类A的引用,那么实参可以为其派生类的对象,系统自动完成类型转换。

    void play(Student &B)
    {
    	B.print();
    }
    
    UnderGraduate A("LiMing", 20, 10005, 100);
    
    play(A);
    

    5.指向基类对象的指针也可以指向派生类对象。即 派生类对象的地址可以赋值给指向其基类的指针。
    指向基类的指针变量 只能访问 派生类对象 的 继承基类的部分,不能访问 派生类增加的成员

    关于public private protected 的问题

    个人认为,protected 是最合适的继承方式,public 继承虽然完整保留了基类,但是在主函数也可以访问其继承下来的基类成员,不利于封装性。 private 继承只能在其派生类里访问基类成员,而且根据上文的表格,其类型均为private,导致其派生类访问基类的成员很不方便。折中之下,protected 继承既有利于保护封装性,也让派生类方便访问其继承的基类成员。

  • 相关阅读:
    寒假记录九
    寒假记录八
    寒假记录七
    Powershell 检测USB存储设备
    [轉載] AttributeError: module 'comtypes.gen.UIAutomationClient' has no attribute 'IUIAutomation'
    使用Pyinstaller对Python文件打包
    Python使用uiautomation实现Windows平台自动化
    Python 相對路徑
    Python使用Win32com實現 Excel多個Sheet截圖
    JavaScript 提取网页数据
  • 原文地址:https://www.cnblogs.com/qq952693358/p/5597981.html
Copyright © 2020-2023  润新知