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
相关推荐
磊 子34 分钟前
STL之deque和list以及两者与vector的对比
开发语言·c++·list
郝学胜_神的一滴38 分钟前
CMake 012:Linux 下动态库与可执行程序的单文件构建
c++·cmake
小poop1 小时前
操作符详解:从入门到精通
c++
山上三树1 小时前
C/C++ 高频报错速查表(开发通用版)
c语言·开发语言·c++
Tian_Hang1 小时前
Factory Method | 工厂方法
开发语言·c++
elseif1232 小时前
【C++】vector 详细版
开发语言·c++·算法
cany10002 小时前
C++ -- 原子变量
c++
cany10003 小时前
C++ -- 队列std::queue
开发语言·c++
周末也要写八哥3 小时前
C++中单线程方式之无脑上锁
java·开发语言·c++
cany10003 小时前
C++ -- 动态内存分配和释放(new/delete)
开发语言·c++