zoukankan      html  css  js  c++  java
  • (12)C++ 继承

      

    1继承语法

    class Base {
    public:
        void print() {
            cout << "Base" << endl;
        }
    };
    
    class Sun : public Base {
    
    };
    
    int main() {
        Sun s;
        s.print();
    }

    2继承访问权限

     子类继承父类时,会根据继承的三种方式改变子类继承成员的访问权限

    3.继承模型

    父类的所有成员变量和函数都会被子类继承,但会根据权限不同有的不能被调用

    查看方式:

    (1)打开开发者命令提示符

    从windows开始中打开

     (2)跳转到文件路径

    (3)cl /d1 reportSingleClassLayout类名 文件名

    cl /d1 reportSingleClassLayoutSun main.cpp

    注意: c后面时英文字母L,d后面是数字one

    class Base {
    public:
        int a;
        void print() {
            cout << "Base" << endl;
        }
    };
    
    class Sun : public Base {
        int b;
    }

     可以看到类内的成员被继承了下来

     4.继承中构造和析构顺序

    class Base {
    public:
        Base() {
            cout << "父类构造" << endl;
        }
        ~Base() {
            cout << "父类析构" << endl;
        }
    };
    
    class Sun : public Base {
    public:
        Sun() {
            cout << "子类构造" << endl;
        }
        ~Sun() {
            cout << "子类析构" << endl;
        }
    };
    
    int main() {
        {
            Sun s;
        }
    }

     生命周期符合栈的方式

    5.父类和子类的调用

    子类如果想要调用父类的成员变量或成员函数需要加作用域

    class Base {
    public:
        void print() {
            cout<<"父类"<<endl;
        }
    };
    
    class Sun : public Base {
    public:
        void print() {
            cout << "子类" << endl;
        }
    };
    
    int main() {
        {
            Sun s;
            s.print();
            s.Base::print();//方法子类对象父类需要加作用域
        }
    }

    静态的规则也相同

    5.多继承

    class Base1 {
    public:
        void print() {
            cout<<"父类1"<<endl;
        }
    };
    
    class Base2 {
    public:
        void print() {
            cout << "父类2" << endl;
        }
    };
    
    class Sun : public Base1, public Base2{
    public:
        void print() {
            cout << "子类" << endl;
        }
    };

     小心不同父类出现同名的情况

  • 相关阅读:
    dataframe字段过长被截断
    sublime text 3安装Anaconda插件之后写python出现白框
    在tkinter中使用matplotlib
    RemoteDisconnected: Remote end closed connection without response
    object of type 'Response' has no len()
    matploylib之热力图
    pycharm格式化python代码快捷键Ctrl+Alt+L失效
    Windows下Redis集群配置
    七牛云--对象存储
    Spring发送邮件
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/11606102.html
Copyright © 2011-2022 走看看