演练:使用项目和解决方案 (C++)Walkthrough: Working with Projects and Solutions (C++)

此处介绍如何在 Visual Studio 中创建 C++ 项目,添加代码,然后生成并运行该项目。Here's how to create a C++ project in Visual Studio, add code, and then build and run the project. 本演练中的项目是一个程序,该程序跟踪正在玩各种纸牌游戏的玩家数量。The project in this walkthrough is a program that tracks how many players are playing different card games.

在 Visual Studio 中,可以将工作组织为项目和解决方案。In Visual Studio, work is organized in projects and solutions. 一个解决方案可以包含多个项目,例如,一个 DLL 和一个引用该 DLL 的可执行文件。A solution can have more than one project—for example, a DLL and an executable that references that DLL. 有关详细信息,请参阅解决方案和项目For more information, see Solutions and Projects.

准备工作Before you start

若要完成本演练,需要 Visual Studio 2017 或更高版本。To complete this walkthrough, you need Visual Studio 2017 or later. 如果需要副本,下面是简要指南:在 Visual Studio 中安装 C++ 支持If you need a copy, here's a short guide: Install C++ support in Visual Studio. 如果尚未安装,请按照通过“Hello, World”教程完成安装后的后续步骤操作,确保 C++ 组件正确安装且正常工作。If you haven't done it yet, follow the next steps after installation through the "Hello, World" tutorial to make sure the C++ components are installed correctly and it all works.

了解 C++ 语言的基础知识以及编译器、链接器和调试程序的用途会很有帮助。It helps if you understand the fundamentals of the C++ language, and know what a compiler, linker, and debugger are used for. 本教程还假定你熟悉 Windows 及其菜单、对话框的使用方式。The tutorial also assumes that you're familiar with Windows and how to use menus, dialogs,

创建项目Create a project

若要创建项目,请先选择项目类型模板。To create a project, first choose a project-type template. 对于每种项目类型,Visual Studio 会设置编译器设置,并根据类型生成起始代码,稍后可修改该代码。For each project type, Visual Studio sets compiler settings and—depending on the type—generates starter code that you can modify later. 根据使用的 Visual Studio 版本,以下步骤会有所不同。The following steps vary depending on which version of Visual Studio you are using. 若要查看 Visual Studio 首选项的文档,请使用“版本”选择器控件。To see the documentation for your preferred version of Visual Studio, use the Version selector control. 它位于此页面上目录表的顶部。It's found at the top of the table of contents on this page.

在 Visual Studio 2019 中创建项目To create a project in Visual Studio 2019

  1. 在主菜单中,依次选择“文件”>“新建”>“项目”,以打开“新建项目”对话框。From the main menu, choose File > New > Project to open the Create a New Project dialog box.

  2. 在对话框顶部,将“语言” 设置为“C++” ,将“平台” 设置为“Windows” ,并将“项目类型” 设置为“控制台” 。At the top of the dialog, set Language to C++, set Platform to Windows, and set Project type to Console.

  3. 从筛选的项目类型列表中,选择“控制台应用”,然后选择“下一步” 。From the filtered list of project types, choose Console App then choose Next. 在下一页中,输入“游戏”作为项目名称。In the next page, enter Game as the name for the project.

    可以接受“位置”下拉列表中的默认位置、输入其他位置或者选择“浏览”按钮,浏览要保存项目的目录 。You can accept the default location in the Location drop-down list, enter a different location, or choose the Browse button to browse to a directory where you want to save the project.

    创建项目时,Visual Studio 将该项目放入一个解决方案。When you create a project, Visual Studio puts the project in a solution. 默认情况下,解决方案的名称与项目名称相同。By default, the solution has the same name as the project. 可以更改“解决方案名称”框中的名称,但是对于此示例,请保留默认名称。You can change the name in the Solution name box, but for this example, keep the default name.

  4. 选择“创建”按钮创建项目。Choose the Create button to create the project.

    Visual Studio 创建新的解决方案和项目文件,并为它生成的 Game.cpp 源代码文件打开编辑器。Visual Studio creates your new solution and project files, and opens the editor for the Game.cpp source code file it generated.

在 Visual Studio 2017 中创建项目To create a project in Visual Studio 2017

  1. 在菜单栏上,依次选择“文件”>“新建”>“项目”。On the menu bar, choose File > New > Project.

  2. 在“新建项目”对话框的左窗格中展开“已安装”,并选择“Visual C++”(如果它尚未打开) 。In the left pane of the New Project dialog box, expand Installed and select Visual C++, if it isn't open already.

  3. 在中间窗格的已安装模板列表中,选择“Windows 控制台应用程序”。In the list of installed templates in the center pane, select Windows Console Application.

  4. 在“名称”框中输入项目的名称。Enter a name for the project in the Name box. 对于此示例,请输入“游戏”。For this example, enter Game.

    可以接受“位置”下拉列表中的默认位置、输入其他位置或者选择“浏览”按钮,浏览要保存项目的目录 。You can accept the default location in the Location drop-down list, enter a different location, or choose the Browse button to browse to a directory where you want to save the project.

    创建项目时,Visual Studio 将该项目放入一个解决方案。When you create a project, Visual Studio puts the project in a solution. 默认情况下,解决方案的名称与项目名称相同。By default, the solution has the same name as the project. 可以更改“解决方案名称”框中的名称,但是对于此示例,请保留默认名称。You can change the name in the Solution name box, but for this example, keep the default name.

  5. 选择 “确定” 按钮,创建单元测试项目。Choose the OK button to create the project.

    Visual Studio 创建新的解决方案和项目文件,并为它生成的 Game.cpp 源代码文件打开编辑器。Visual Studio creates your new solution and project files, and opens the editor for the Game.cpp source code file it generated.

在 Visual Studio 2015 中创建项目To create a project in Visual Studio 2015

  1. 在菜单栏上,依次选择“文件”>“新建”>“项目”。On the menu bar, choose File > New > Project.

  2. 在“新建项目”对话框的左窗格中展开“已安装”,并选择“Visual C++”(如果它尚未打开) 。In the left pane of the New Project dialog box, expand Installed and select Visual C++, if it isn't open already.

  3. 在中间窗格的已安装模板列表中,选择“Win32 控制台应用程序”。In the list of installed templates in the center pane, select Win32 Console Application.

  4. 在“名称”框中输入项目的名称。Enter a name for the project in the Name box. 对于此示例,请输入“游戏”。For this example, enter Game.

    可以接受“位置”下拉列表中的默认位置、输入其他位置或者选择“浏览”按钮,浏览要保存项目的目录 。You can accept the default location in the Location drop-down list, enter a different location, or choose the Browse button to browse to a directory where you want to save the project.

    创建项目时,Visual Studio 将该项目放入一个解决方案。When you create a project, Visual Studio puts the project in a solution. 默认情况下,解决方案的名称与项目名称相同。By default, the solution has the same name as the project. 可以更改“解决方案名称”框中的名称,但是对于此示例,请保留默认名称。You can change the name in the Solution name box, but for this example, keep the default name.

  5. 选择 “确定” 按钮,创建单元测试项目。Choose the OK button to create the project.

    Visual Studio 创建新的解决方案和项目文件,并为它生成的 Game.cpp 源代码文件打开编辑器。Visual Studio creates your new solution and project files, and opens the editor for the Game.cpp source code file it generated.

组织项目和文件Organize projects and files

可以使用“解决方案资源管理器”来组织和管理解决方案中的项目、文件及其他资源。You can use Solution Explorer to organize and manage the projects, files, and other resources in your solution.

本部分演练演示如何将类添加到项目中。This part of the walkthrough shows how to add a class to the project. 添加类时,Visual Studio 添加相应的 .h 和 .cpp 文件。When you add the class, Visual Studio adds the corresponding .h and .cpp files. 可以在“解决方案资源管理器”中查看结果。You can see the results in Solution Explorer.

向项目添加类To add a class to a project

  1. 如果 Visual Studio 中未显示“解决方案资源管理器”窗口,请在菜单栏上选择“视图” > “解决方案资源管理器”。If the Solution Explorer window isn't displayed in Visual Studio, on the menu bar, choose View > Solution Explorer.

  2. 在“解决方案资源管理器”中,选择“游戏”项目 。In Solution Explorer, select the Game project. 在菜单栏上选择“项目” > “添加类”。On the menu bar, choose Project > Add Class.

  3. 在“添加类”对话框中的“类名”框内输入“Cardgame”。In the Add Class dialog, enter Cardgame in the Class Name box. 请勿修改默认的文件名和设置。Don't modify the default file names and settings. 选择“确定” 按钮。Choose the OK button.

    Visual Studio 创建新的文件并将其添加到项目。Visual Studio creates new files and adds them to your project. 可以在“解决方案资源管理器”窗口中查看这些文件。You can see them in the Solution Explorer window. Cardgame.h 和 Cardgame.cpp 文件在编辑器中打开。The Cardgame.h and Cardgame.cpp files are opened in the editor.

  4. 编辑 Cardgame.h 文件,并进行以下更改:Edit the Cardgame.h file, and make these changes:

    • 在类定义的左大括号之后添加两个私有数据成员。Add two private data members after the opening brace of the class definition.

      int players;
      static int totalParticipants;
      
    • 修改 Visual Studio 生成的默认构造函数。Modify the default constructor that Visual Studio generated. public: 访问说明符之后,将发现如下所示的行:After the public: access specifier, find the line that looks like:

      Cardgame();

      将构造函数修改为,接受一个类型为 int 的名为“players”的参数。Modify the constructor to take one parameter of type int, named players.

      Cardgame(int players);

    • 在默认析构函数之后,为名为 GetParticipants 的 static int 成员函数添加内联声明,该成员函数没有参数且返回 totalParticipants 值。After the default destructor, add an inline declaration for a static int member function named GetParticipants that takes no parameters and returns the totalParticipants value.

      static int GetParticipants() { return totalParticipants; }

    在你对 Cardgame.h 文件进行更改之后,该文件应类似于以下代码:The Cardgame.h file should resemble the code below after you change it:

    #pragma once
    class Cardgame
    {
        int players;
        static int totalParticipants;
    public:
        Cardgame(int players);
        ~Cardgame();
        static int GetParticipants() { return totalParticipants; }
    };
    

    #pragma once 行通知编译器仅包含一次头文件。The line #pragma once tells the compiler to include the header file only one time. 有关详细信息,请参阅 onceFor more information, see once. 有关上述头文件中其他 C++ 关键字的信息,请参阅int静态公共For information about other C++ keywords in the header file above, see class, int, static, and public.

  5. 选择编辑窗格顶部的“Cardgame.cpp”选项卡,打开它进行编辑。Choose the Cardgame.cpp tab at the top of the editing pane to open it for editing.

  6. 删除文件中的所有内容,并将其替换为以下代码:Delete everything in the file and replace it with the code:

    #include "pch.h" // remove this line in Visual Studio 2019
    #include "Cardgame.h"
    #include <iostream>
    
    using namespace std;
    
    int Cardgame::totalParticipants = 0;
    
    Cardgame::Cardgame(int players)
        : players(players)
    {
        totalParticipants += players;
        cout << players << " players have started a new game.  There are now "
             << totalParticipants << " players in total." << endl;
    }
    
    Cardgame::~Cardgame()
    {
    }
    

    备注

    输入代码时,可以使用自动完成功能。You can use auto-completion when you are entering code. 例如,如果使用键盘输入此代码,可以输入 pl 或 tot,然后按 Ctrl+空格键。For example, if you enter this code at the keyboard, you can enter pl or tot and then press Ctrl+Spacebar. 自动完成功能可为你输入 playerstotalParticipantsAuto-completion enters players or totalParticipants for you.

向主函数添加测试代码Add test code to your main function

向应用添加一些测试新函数的代码。Add some code to your app that tests the new functions.

向项目添加测试代码To add test code to the project

  1. 在 Game.cpp 编辑器窗口中,用下列代码替换现有代码:In the Game.cpp editor window, replace the existing code with:

    // Game.cpp : Defines the entry point for the console application.
    //
    
    #include "pch.h" // remove this line in Visual Studio 2019
    #include "Cardgame.h"
    #include <iostream>
    
    using namespace std;
    
    void PlayGames()
    {
        Cardgame bridge(4);
        Cardgame blackjack(8);
        Cardgame solitaire(1);
        Cardgame poker(5);
    }
    
    int main()
    {
        PlayGames();
        return 0;
    }
    

    此代码会将测试函数 PlayGames 添加到源代码,并在 main 中调用。The code adds a test function, PlayGames, to the source code, and calls it in main.

生成并运行应用项目Build and run your app project

接下来,生成项目并运行应用。Next, build the project and run the app.

生成并运行此项目To build and run the project

  1. 在菜单栏上,依次选择“生成” > “生成解决方案” 。On the menu bar, choose Build > Build Solution.

    来自生成的输出显示在“输出”窗口中。Output from a build is displayed in the Output window. 如果生成成功,输出应类似于:If your build is successful, the output should resemble:

    1>------ Build started: Project: Game, Configuration: Debug Win32 ------
    1>pch.cpp
    1>Cardgame.cpp
    1>Game.cpp
    1>Generating Code...
    1>Game.vcxproj -> C:\Users\<username>\source\repos\Game\Debug\Game.exe
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
    

    “输出”窗口可以根据不同的生成配置显示不同步骤,但是如果项目生成成功,最后一行应类似于上面显示的输出。The Output window can show different steps, depending on the build configuration, but if the project build succeeds, the last line should resemble the output shown.

    如果生成未成功,请将你的代码与前面步骤中显示的代码进行比较。If your build didn't succeed, compare your code to the code that is shown in the earlier steps.

  2. 要运行项目,请在菜单栏上选择“调试” > “开始执行(不调试)”。To run the project, on the menu bar, choose Debug > Start Without Debugging. 应显示控制台窗口,并且其输出应类似于:A console window should appear, and the output should resemble:

    4 players have started a new game.  There are now 4 players in total.
    8 players have started a new game.  There are now 12 players in total.
    1 players have started a new game.  There are now 13 players in total.
    5 players have started a new game.  There are now 18 players in total.
    

    按任意键关闭控制台窗口。Press a key to dismiss the console window.

恭喜,你已成功生成应用项目和解决方案。Congratulations, you've successfully built an app project and solution. 继续完成本演练,详细了解如何在 Visual Studio 中生成 C++ 代码项目。Continue the walkthrough to learn more about how to build C++ code projects in Visual Studio.

后续步骤Next steps

上一步:使用 Visual Studio IDE 进行 C++ 桌面开发Previous: Using the Visual Studio IDE for C++ Desktop Development
下一篇: 演练:生成项目 (C++)Next: Walkthrough: Building a Project (C++)

请参阅See also

C++ 语言参考C++ Language Reference
项目和生成系统Projects and build systems