目录
设计士兵类,创建相应的soldier.h和soldier.cpp
构建main.cpp调用soldier.cpp和gun.cpp中两个类的实现函数;
项目需求
士兵突击:
1、士兵许三多有一把枪,叫做AK47;
2、士兵可以开火;
3、士兵可以给枪装填子弹;
4、枪能够发射子弹;
5、枪能够装填子弹——增加子弹数量
项目分析:
1、开发两个类:士兵类、枪类;
2、先设计哪个类: 应该先设计枪类,因在士兵类中有一个枪类指针Gun* _ptr_gun;也就是说士兵类中要包含枪类;
合理设置项目目录
创建工程文件7,并在ubuntu下用VScode打开;
创建include文件夹放头文件;创建src文件夹放源文件;
编写项目源文件
先对gun类进行设计,创建对应的.h文件和.cpp文件;
Gun.h
#pragma once //防止头文件重复包含
#include<string>
class Gun
{
public:
//构造函数初始化,构造函数直接在头文件中实现
Gun(std:: string type){
this->_bullet_count=0;
this->_type=type;
}
//装填子弹
void addBullet(int bullet_num);
//发射子弹的接口
bool shoot();
private:
int _bullet_count;
std:: string _type;
};
Gun.cpp
//.cpp文件写接口函数的实现
#include "Gun.h"
#include<iostream>
using namespace std;
void Gun::addBullet(int bullet_num)
{
this-> _bullet_count+=bullet_num;
}
bool Gun::shoot()
{
if(_bullet_count<=0)
{
cout<<" here is no bullet!"<<endl;
return false; //直接返回,程序结束
}
cout<<" fire work"<<endl;
this->_bullet_count-=1;
return true;
}
结果如下:
设计士兵类,创建相应的soldier.h和soldier.cpp
soldier.h
#pragma once
#include <string>
#include "Gun.h"
class Soldier
{
public:
Soldier(std::string name); //构造函数不在头文件中实现
//因为定义了指针,故构造析构函数
~Soldier();
//为士兵添加一把枪
void addGun(Gun* ptr_gun );
//为枪增加子弹的接口
void addBulletToGun(int num);
bool fire();
private:
std::string _name; //头文件中必须写std
Gun *_ptr_gun;
};
soldier.cpp
#include "Soldier.h"
#include<iostream>
Soldier::Soldier(std::string name ) //构造函数没有返回值
{
this->_name=name;
this->_ptr_gun=nullptr; //初始化为空指针
}
void Soldier::addGun(Gun* ptr_gun)
{
this->_ptr_gun=ptr_gun;
}
void Soldier::addBulletToGun(int num)
{
this->_ptr_gun->addBullet(num);
}
bool Soldier::fire()
{
return this->_ptr_gun->shoot();
}
//析构函数,释放指针
Soldier::~Soldier()
{
if(this->_ptr_gun==nullptr)
{
return;
}
delete this->_ptr_gun;
this->_ptr_gun=nullptr;
}
构建main.cpp调用soldier.cpp和gun.cpp中两个类的实现函数;
main.cpp与include和src处于同一级目录
main.cpp
#include "Gun.h"
#include "Soldier.h"
//测试函数, 实现一些测试功能
void test()
{
Soldier sandu("xusanduo"); //实例化Soldier类
sandu.addGun(new Gun("AK47")); //要传入一个gun,需要先创建一个出来,也就是new一个
sandu.addBulletToGun(20);
sandu.fire( );
}
int main( )
{
test( );
return 0;
}
g++方式编译工程文件
打开终端查看工程文件目录结构;
编译main函数和其余两个.cpp文件;生成可执行文件myexe
编译时可以添加其它参数;-g -O2 -Wall
CMake方式编译工程文件
在工程文件顶层目录创建并编写CMakeLists.txt;
便于区别将g++编译方式生成的可执行文件rename为myg++exe; 直接删除刚刚g++编译方式生成的中间文件,仅保留下列文件,以便于用cmak方式构建工程;
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
#添加 -g -O2 std+=c11 -W all等编译参数选项
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O2 -Wall")
project(SOIDIERFIRE)
#等价于-Iinclude 搜索头文件路径
#include是相对于CMakeLists.txt的相对路径
#绝对路径写法:include_directories(${CMAKE_SOURCE_DIR/include})
#CMAKE_SOURCE_DIR等价于工程文件7,类似于根目录
include_directories(include)
add_executable(my_cmake_exe main.cpp src/Gun.cpp src/Soldier.cpp)
操作技巧,将终端切换到右端,右键点击move panel right
创建build文件,并进入build;
执行cmake ..
执行make命令
运行生成的target文件my_cmake_exe
修改main.cpp文件内容,再次make
对main.cpp文件进行修改后,只需要重新执行make命令(make时只会对做了更改的.cpp 文件进行重新编译,重新生成main.cpp.o)
重新运行my_cmake_exe文件
注意:无论是对.cpp文件还是CMakeLists.txt中的内容做了修改,都只需要重新执行一次make命令即可再次运行 target文件;