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
相关推荐
小师兄吃牛肉5 分钟前
C++ 与 Lua 的协程交互:从原理到实战
c++·lua·交互
YYYing.15 分钟前
【设计模式系列 (八) 】组合模式
c++·后端·设计模式·组合模式·c/c++
艾莉丝努力练剑22 分钟前
【QT】系统相关:多线程QThread基础
开发语言·网络·c++·qt·学习·大模型
l1t26 分钟前
DeepSeek总结的PIVCO-Huffman编码性能优化
数据结构·c++·算法
王维同学1 小时前
ETW监控-KswordARK功能展示
c++·windows·安全
東隅已逝,桑榆非晚1 小时前
c++模板进阶
开发语言·c++·笔记·学习
左手の明天10 小时前
SLIP 协议封装与解析详解:原理、C 代码与实战案例
linux·c语言·开发语言·c++
青少儿编程课堂10 小时前
后缀自动机解析:本质不同子串与最长重复片段统计
c++·python·算法·bfs·信息学竞赛
朝朝辞暮i10 小时前
C++ 第 12 课:局部变量、作用域、变量生命周期
开发语言·c++·算法