using 与 派生

using

  1. 可以用在派生类中用于恢复由 ‘继承方式’ 改变的成员访问属性如下
class Person
{
    protected:
        int age;
    public:
        Person(){}
        void disp(){}
};

class Student : public Person
{
    using Person::age;  //这样就使本来在此类中公有的age又恢复成基类的属性了(保护protected)
    using Person::disp;
}

  1. 为子对象初始化时如果不显示调用,此对象类的构造函数,则系统会提供一个默认的无参的构造函数

派生类构造函数

多重继承时构造次序

class student : Person, Children //默认私有继承
{
student():Children(),Person()//纵然先写children但由于先声明Person所以先构造Person.!!
}


做三件事:

  1. 先调用基类构造函数
  2. 调用子对象的构造函数(如果有的话)
  3. 调用自身

#include <iostream>
#include <cstring>
using namespace std;

class Person  
{
    protected:
        string name;
        int age;

    public:
        Person():name("boss"), age(18){
            cout << "Person()..." << endl;
        }
        Person(string s, int a){
            name = s;
            age = a;

            cout << "Person(string, int)..." << endl;
        }

        ~Person(){
            cout << "~person()..." << endl;
        }

        void disp()
        {
            cout << "father..." << endl;
        }
};

class Student : public Person
{
    public:
        Student(){ 
            code = 0;
            score = 60;
            cout << "Student() ..." << endl; 
        }

        //p是Person的子对象 :构造函数执行顺序:        先基类-->后子对象对应的-->最后派生类的 constructor
        Student(string s,int a, int c, double s3)
            :p(s,a), Person(), code(c),score(s3){
            cout << "Student(,,,)" << endl;
        //Person(s, a); 老师说无法调用构造函数可这儿就可以

        }

        ~Student(){
            cout << "~Student()..." << endl; 
        }

        void disp() const{
            cout << "child..." << endl;
        }

    private:
        int code;
        double score;
        Person p;
};


int main()
{
    Student s2("emploee", 23, 3, 12.1);
//  s2.~Person(); //也可以显示的调用析构函数
//  s2.~Student();
    s2.Person::disp(); //用::调用重写了的父类函数

//  s2.disp();


    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值