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
相关推荐
史迪仔01123 小时前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
会编程的土豆4 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
低频电磁之道4 小时前
解决 Windows C++ DLL 导出类不可见的编译错误
c++·windows
君义_noip6 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
Ricky_Theseus6 小时前
静态链接与动态链接
c++
澈2077 小时前
双指针,数组去重
c++·算法
小辉同志7 小时前
207. 课程表
c++·算法·力扣·图论
feng_you_ying_li7 小时前
C++11,{}的初始化情况与左右值及其引用
开发语言·数据结构·c++
小樱花的樱花8 小时前
打造高效记事本:UI设计到功能实现
开发语言·c++·qt·ui
零二年的冬8 小时前
epoll详解
java·linux·开发语言·c++·链表