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;
}
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐