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
相关推荐
aaPIXa6221 分钟前
C++大型项目模块化拆分实战记录
开发语言·c++
石山代码9 分钟前
C++23 新特性在 CLion 中的实战体验
开发语言·c++·c++23
在线OJ的阿川20 分钟前
仿muduo库实现高并发服务器
linux·服务器·c++
坚定学代码37 分钟前
C++ SOLID 原则(上):单一职责、开闭原则与里氏替换
c++
ysa0510301 小时前
【板子】欧拉序
c++·笔记·算法·深度优先·图论
不负岁月无痕1 小时前
STL -- C++ 红黑树封装 Map 和 Set
java·c语言·开发语言·c++·面试
初学者,亦行者1 小时前
算法设计与分析:动态规划 - TSP问题和0-1背包问题
c++·算法·动态规划
十五年专注C++开发1 小时前
C++之std::numeric_limits介绍
开发语言·c++·limits
拳里剑气2 小时前
C++算法:优先级队列
开发语言·c++·算法·优先级队列
从零开始的代码生活_2 小时前
C++ 模板入门:函数模板、类模板与实例化机制
开发语言·c++·后端