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
相关推荐
乐观勇敢坚强的老彭几秒前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
2301_777998341 小时前
C/C++:预处理详解
c语言·c++
t-think1 小时前
C++类和对象详解(一)
开发语言·c++
阿米亚波3 小时前
【C++ STL】std::unordered_multiset
开发语言·数据结构·c++·笔记·stl
随意起个昵称3 小时前
贪心模型-Johnson法则
c++·算法
蜡笔小马3 小时前
【保姆级教程】Windows 下 CGAL 6.2 + VS2022 全流程实战:从源码编译到项目集成(附避坑指南)
c++·cgal
xiaoye-duck3 小时前
《Linux系统编程》Linux 系统多线程(八): C++ 高并发线程池全链路深度解析与从零手撕实现
linux·c++·线程池
胖大和尚4 小时前
在C++的类中,是否可以把函数声明成__device__
c++·cuda
十年磨剑走天涯4 小时前
C++ STL 容器操作复杂度速查表
开发语言·c++
ziguo11224 小时前
Windows API MessageBox 函数详解
c语言·c++·windows·visualstudio