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
相关推荐
布莱克6056 分钟前
A* 算法详解:从原理到实现
开发语言·c++·算法
多弗朗皮卡丘7 分钟前
C++ 智能指针
开发语言·c++·c++11·智能指针
进化中的刀盾兽25 分钟前
从零实现 C++ AI 大模型接入 SDK(十):SessionManager 会话管理与多轮对话实现
c++
小成2023032026528 分钟前
C++~02运算符重载
开发语言·c++
郑同学的笔记1 小时前
【c++随笔30】C++ 注册回调函数
开发语言·c++
lengxuenong2 小时前
树状数组 · 信息学学习手册2-离散化与逆序对
c++·学习·算法
十二2 小时前
【洛谷题解】P1115 最大子段和(前缀和 + 维护最小前缀)
数据结构·c++·算法·蓝桥杯
cu1434 小时前
细谈IT65631的具体功能与其应用
c++·单片机·嵌入式硬件
幻智星科技4 小时前
Karatsuba与CSD优化FPGA大数乘法
c++·fpga开发·密码学
flower9803234 小时前
C++消息总线软件开发框架AI重构版
c++·设计模式·架构