C++之面向对象编程多文件文件示例

  • 一般将类的声明放在.h文件中,类中成员函数的定义放在.cpp文件中
cpp 复制代码
/*person.h*/
#ifndef __PERSON_H__
#define __PERSON_H__

#include <iostream>
using namespace std;

class person{
private:
    int age;
    string name;
public:
    person(int age, const string& name);
    void whoami(void);
};

#endif
cpp 复制代码
/*person.cpp*/
#include "person.h"

person::person(int age, const string& name){
    this->age = age;
    this->name = name;
}
void person::whoami(void){
    cout << "我是: " << name << endl;
}
cpp 复制代码
#ifndef __STUDENT_H__
#define __STUDENT_H__

#include "person.h"

class student: public person{
private:
    float score;
public:
    student(int age, const string& name, float score);
    void whoami(void);
};

#endif
cpp 复制代码
/*student.cpp*/
#include "student.h"

student::student(int age, const string& name, float score):person(age,name){
    this->score = score;
}
void student::whoami(void){
    person::whoami();
    cout << "我的成绩是: " << score << endl;
}
cpp 复制代码
/*main.cpp*/
#include "student.h"

int main(void){
    student s1(22, "刘备", 81.5);
    s1.whoami();
    return 0;
}
bash 复制代码
g++ person.cpp student.cpp main.cpp
./a.out
相关推荐
汉克老师4 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
智者知已应修善业7 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
云泽8088 小时前
C++11 核心特性全解:列表初始化、右值引用与移动语义实战
开发语言·c++
AI进化营-智能译站9 小时前
ROS2 C++开发系列12-用多态与虚函数构建可扩展的ROS2机器人行为模块
开发语言·c++·ai·机器人
Morwit9 小时前
QML组件之间的通信方案(暴露子组件)
c++·qt·职场和发展
qeen879 小时前
【数据结构】建堆的时间复杂度讨论与TOP-K问题
c语言·数据结构·c++·学习·
图码10 小时前
如何用多种方法判断字符串是否为回文?
开发语言·数据结构·c++·算法·阿里云·线性回归·数字雕刻
handler0110 小时前
Linux 内核剖析:进程优先级、上下文切换与 O(1) 调度算法
linux·运维·c语言·开发语言·c++·笔记·算法
zhouwy11310 小时前
Linux进程与线程编程详解
linux·c++
A7bert77711 小时前
【YOLOv8pose部署至RDK X5】模型训练→转换bin→Sunrise 5部署
c++·python·深度学习·yolo·目标检测