C++中的继承类构造函数

C++中的继承类构造函数注意事项

构造原则如下:
1. 如果子类没有定义构造方法,则调用父类的无参数的构造方法。
2. 如果子类定义了构造方法,不论是无参数还是带参数,在创建子类的对象的时候,首先执行父类无参数的构造方法,然后执行自己的构造方法。
3. 在创建子类对象时候,如果子类的构造函数没有显示调用父类的构造函数,则会调用父类的默认无参构造函数。
4. 在创建子类对象时候,如果子类的构造函数没有显示调用父类的构造函数且父类自己提供了无参构造函数,则会调用父类自己的无参构造函数。
5. 在创建子类对象时候,如果子类的构造函数没有显示调用父类的构造函数且父类只定义了自己的有参构造函数,则会出错(如果父类只有有参数的构造方法,则子类必须显示调用此带参构造方法)。
6. 如果子类调用父类带参数的构造方法,需要用初始化父类成员对象的方式

关键代码举例
class People
{
    public:
        virtual void print();
        People(string nm);
        void getID(int num);
    protected:
        int ID;
        string name;
};


class Student : public People
{   
    public:
        void print();
        Student(string sch);
    private:
        string school;
        //string name;
};


People::People(string nm)
{
    name = nm;
}

//子类必须显示的调用父类的带参数构造函数
Student::Student(string sch) : People("yzj")
{
    school = sch;
}

完整代码

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

class People
{
    public:
        virtual void print();
        People(string nm);
        void getID(int num);
    protected:
        int ID;
        string name;
};


class Student : public People
{   
    public:
        void print();
        Student(string sch);
    private:
        string school;
        //string name;
};


People::People(string nm)
{
    name = nm;
}


Student::Student(string sch) : People("yzj")//子类必须显示的调用父类的带参数构造函数
{
    school = sch;
}

void People::print()
{
    cout << "The name is " << name << endl;
    cout << "The ID is " << ID << endl;
}

void People::getID(int num)
{
    ID = num;
}

void Student::print()
{
    cout << "The name is " << name << endl;
    cout << "The school is " << school << endl;
}

int main()
{
    People people("lzq");
    people.getID(123);
    Student student("MaEr");
    people.print();
    student.print();

    return 0;
}

输出
在这里插入图片描述

总结

  1. 在类的继承的过程中,如果子类没有定义构造函数,程序就会自动调用父类的构造函数。
  2. 如果子类定义了构造函数且父类是无参的构造函数,那么创建类的时候会自动先调用父类的构造函数,再调用子类的构造函数。
  3. 如果子类定义了构造函数且没有显示调用父类中唯一的带参构造函数,程序会报错。
  4. 调用父类构造函数的时候得用初始化父类成员对象的方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值