第七讲:【实战】使用 VSCode 进行完整项目开发
案例:士兵突击
需求:
1. 士兵 许三多 有一把 枪 ,叫做 AK47
2. 士兵 可以 开火
3. 士兵 可以 给枪装填子弹
4. 枪 能够 发射 子弹
5. 枪 能够 装填子弹 —— 增加子弹数量
开发:
开发枪类
开发士兵类
7.1 合理设置项目目录
7.2 编写项目源文件
/include Gun.h
#pragma once
#include <iostream>
using namespace std;class Gun {public:Gun(string type) {this->_bullet_count = 0;this->_type = type;}void addBullet(int bullet_num);bool shoot();private:int _bullet_count;string _type;
};
include/ Solider.h
#pragma once
#include "Gun.h"
#include <iostream>
using namespace std;class Solider {public:Solider(string name);void addBulletToGun(int num);void addGun(Gun *ptr_gun);bool fire();~Solider();private:string _name;Gun *_ptr_gun;
};
/src Gunc.cpp
#include "../include/Gun.h"void Gun::addBullet(int bullet_num) { this->_bullet_count += bullet_num; }bool Gun::shoot() {if (this->_bullet_count <= 0) {cout << "there is no bullet" << endl;return false;}this->_bullet_count -= 1;cout<<"shoot successfully"<<endl;return true;
}
/src Solider.cpp
#include "../include/Solider.h"Solider::Solider(string name) {this->_name = name;this->_ptr_gun = nullptr;
}
void Solider::addBulletToGun(int num) { this->_ptr_gun->addBullet(num); }bool Solider::fire() {this->_ptr_gun->shoot();return false;
}void Solider::addGun(Gun *ptr_gun) { this->_ptr_gun = ptr_gun; }Solider::~Solider() {if (this->_ptr_gun == nullptr) {return;} else {delete _ptr_gun;_ptr_gun = nullptr;}
}
7.3 编写CMakeLists.txt构建项目编译规则
cmake_minimum_required(VERSION 3.0)
project(soliderFile)
#头文件
# include_directories(include)
include_directories(${CMAKE_SOURCE_DIR}/include)set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")set(CMAKE_BUILD_TYPE Debug)add_executable(my_cmake_main main.cpp src/Gun.cpp src/Solider.cpp)
7.4 使用外部构建,手动编译CMake项目
mkdir build ->cd build -> cmake .. -> make
7.5 配置VSCode的json文件并调试项目
launch.json
{// Use IntelliSense to learn about possible attributes.// Hover to view descriptions of existing attributes.// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387"version": "0.2.0","configurations": [{"name": "g++ - Build and debug active file","type": "cppdbg","request": "launch",//绝对路径最重要。"program": "${workspaceFolder}/self_study2/7/build/my_cmake_main","args": [],"stopAtEntry": false,"cwd": "${workspaceFolder}","environment": [],"externalConsole": false,"MIMode": "gdb","setupCommands": [{"description": "Enable pretty-printing for gdb","text": "-enable-pretty-printing","ignoreFailures": true},{"description": "Set Disassembly Flavor to Intel","text": "-gdb-set disassembly-flavor intel","ignoreFailures": true}],//通过这个语句调用task.json 语法。"preLaunchTask": "Build","miDebuggerPath": "/usr/bin/gdb"}]
}
tasks.json
{ "version": "2.0.0","options": {"cwd": "${workspaceFolder}/self_study2/7/build"},"tasks": [{"type": "shell","label": "cmake","command": "cmake","args": [".."]},{"label": "make","group": {"kind": "build","isDefault": true},"command": "make","args": []},{"label": "Build","dependsOrder": "sequence", // 按列出的顺序执行任务依赖项"dependsOn":["cmake","make"]}]}