C++中的分离式编译

    随着程序越来越复杂, 我们希望把程序的各个部分分别存储在不同的文件中。

     我们可以将原来的程序分成三个部分:

  • 头文件: 包含结构声明和使用这些结构的函数的原型。
#pragma once

#ifndef GAME_H_
#define GAME_H_

#include<string>
using namespace std;

struct Game
{
    string gameName;
    float gameScore;
};

void inputGame(Game games[], const int size);
void sort(Game games[], const int size);
void display(const Game games[], const int size);

const int Size = 5;

#endif // !GAME_H_

     头文件中常包含的内容:函数原型、使用#define或const定义的符号常量、结构声明、类声明、模板声明、内联函数

  • 源代码文件: 包含与结构有关的函数的代码。
#include "game.h"
#include <iostream>

void inputGame(Game games[], const int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << "请输入喜爱的游戏的名称: ";
        cin >> games[i].gameName;
        cout << "请输入游戏评分(10以内的小数): ";
        cin >> games[i].gameScore;
    }
}

void sort(Game games[], const int size)
{
    Game temp;
    for (int i = 0; i < size - 1; i++)
    {
        for (int j = i + 1; j < size; j++)
        {
            if (games[i].gameScore < games[j].gameScore)
            {
                temp = games[i];
                games[i] = games[j];
                games[j] = temp;
            }
        }
    }
}

void display(const Game games[], const int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << i + 1 << ": " << games[i].gameName << "(" << games[i].gameScore << ")" << endl;
    }
}
  • 源代码文件: 包含调用与结构相关的函数的代码。
#include"game.h"
#include<iostream>

int main()
{
    cout << "请输入5个你喜爱的游戏的名称,并给他们评分:" << endl;
    Game games[Size] = {};
    inputGame(games, Size);
    sort(games, Size);
    display(games, Size);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiaokunzhang/article/details/80989469