C++当中的子类构造函数后面跟随冒号调用父类构造方法

C++忘得也差不多了,最近突然看到一个可能忘记了的用法来记录一下,就是我子类当中的构造函数要去调用父类的构造方法可以直接通过在类中定义构造函数的时候后面用冒号然后再写上父类构造函数的调用

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>

using namespace std;

class Person{

    public: int age;
    string name;
    //父类构造函数
    Person(int a,string s):age(a),name(s){
        cout<<"hehe"<<endl;
    }
};

class Student:public Person
{
public:
    static int ID;

    //在进行子类初始化的时候使用了父类初始化
    Student() : Person(ID,"saaa"){
        cout<<"哈哈哈"<<endl;
    }
};

int Student::ID=1;

int main()
{
    //创建子类对象
    Student stu = Student();

    cout<<stu.age<<stu.name;
}

猜你喜欢

转载自blog.csdn.net/zcmuczx/article/details/80879522