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
相关推荐
lightqjx14 分钟前
【算法】前缀和
c++·算法·leetcode·前缀和
汉克老师38 分钟前
GESP5级C++考试语法知识(七、链表(二)双链表)
c++·链表·双链表·gesp5级·gesp五级
旖-旎38 分钟前
二分查找(寻找旋转排序数组中的最小值)(7)
c++·算法·二分查找·力扣
C羊驼39 分钟前
C/C++数据结构与算法:穷举法
c语言·c++·笔记·学习·算法
十五年专注C++开发43 分钟前
libuv:一个跨平台的C++异步 I/O 库
开发语言·c++·node.js·libuv·vlibuv
qq_417695051 小时前
C++中的解释器模式
开发语言·c++·算法
xiaoye-duck2 小时前
《算法题讲解指南:动态规划算法--路径问题》--9.最小路径和,10.地下城游戏
c++·算法·动态规划
刺客xs2 小时前
c++模板
java·开发语言·c++
2301_818419012 小时前
C++中的状态模式实战
开发语言·c++·算法
仰泳的熊猫2 小时前
题目2576:蓝桥杯2020年第十一届省赛真题-解码
数据结构·c++·算法·蓝桥杯