在 Visual Studio 中编辑和重构 C++ 代码Edit and refactor C++ code in Visual Studio

Visual Studio 提供了多种用于帮助编写、编辑和重构代码的工具。Visual Studio provides several tools to help you write, edit, and refactor your code.

IntelliSenseIntelliSense

IntelliSense 是一款功能强大的代码完成工具,可在键入时建议符号和代码片段。IntelliSense is a powerful code completion tool that suggests symbols and code snippets for you as you type. Visual Studio 中的 C++ IntelliSense 实时运行,并且会在更新代码库时对其进行分析并提供建议。C++ IntelliSense in Visual Studio runs in real time, analyzing your codebase as you update it and providing recommendations. 在键入更多字符时,推荐结果列表会缩小。As you type more characters, the list of recommended results narrows down.

C++ 成员下拉列表

一些符号会自动省略,帮助减少结果。Some symbols are omitted automatically to help narrow down the results. 例如,在从类外部访问类对象的成员时,默认情况下无法看到私有成员,或者受保护成员(如果不位于子类的上下文中)。For example, when accessing a class object’s members from outside the class, you will not be able to see private members by default, or protected members (if you are not in the context of a child class). 可使用底部的按钮调整筛选。You can adjust the filtering by using the buttons at the bottom.

从下拉列表中选择符号后,可使用 Tab、Enter 或其他某个提交字符(默认情况下:{}.,:;+-*/%&|^!=?@#))自动完成 。After you choose the symbol from the drop-down list, you can autocomplete it with Tab, Enter, or one of the other commit characters (by default: {}.,:;+-*/%&|^!=?@#). 要在此列表中添加或删除字符,请在“快速启动”(Ctrl + Q)中搜索“IntelliSense”,然后选择“文本编辑器”>“C/C++”>“高级”选项 。To add or remove characters from this list, search for "IntelliSense" in Quick Launch (Ctrl + Q) and choose the Text Editor > C/C++ > Advanced option. “成员列表提交字符”选项允许使用所需更改自定义列表 。The Member List Commit Characters option enables you to customize the list with the changes you want.

“成员列表筛选模式”选项控制显示的 IntelliSense 自动完成建议的类型 。The Member List Filter Mode option controls what kinds of IntelliSense autocomplete suggestions you see. 默认情况下,它设置为“模糊” 。By default, it is set to Fuzzy. 在模糊搜索中,如果你有名为 MyAwesomeClass 的符号,则可以键入“MAC”并在自动完成建议中查找该类 。In a fuzzy search, if you have a symbol called MyAwesomeClass, you can type "MAC" and find the class in your autocomplete suggestions. 模糊算法设置了符号要显示在列表中所必须满足的最小阈值。The fuzzy algorithm sets a minimum threshold that symbols must meet to show up in the list. 智能筛选显示包含与键入的内容匹配的 substring 的所有符号 。Smart filtering displays all symbols containing substrings that match what you typed. 前缀筛选搜索以键入的内容开头的字符串 。Prefix filtering searches for strings that begin with what you typed.

有关 C++ IntelliSense 的详细信息,请参阅 Visual C++ IntelliSense配置用于 IntelliSense 的 C++ 项目For more information about C++ IntelliSense, see Visual C++ IntelliSense and Configure a C++ project for IntelliSense.

IntelliCodeIntelliCode

IntelliCode 是 AI 辅助的 IntelliSense。IntelliCode is AI-assisted IntelliSense. 它将最有可能的候选项置于完成列表的顶部。It puts the most likely candidate at the top of your completion list. IntelliCode 建议基于 GitHub 上的数千个开放源代码项目,其中每个项目都有 100 多个星级。IntelliCode recommendations are based on thousands of open source projects on GitHub each with over 100 stars. 在与代码的上下文相结合时,将定制完成列表以推荐常见做法。When combined with the context of your code, the completion list is tailored to promote common practices.

在编写 C++ 时,IntelliCode 可在使用 C++ 标准库等热门库时提供协助。When writing C++, IntelliCode will assist when using popular libraries such as the C++ Standard Library. 代码的上下文用于首先提供最有用的建议。The context of your code is used to provide the most useful recommendations first. 在以下示例中,size 成员函数通常与 sort 函数一起使用,因此它显示在结果列表的顶部。In the following example, the size member function is commonly used with the sort function, so it is surfaced to the top of the results list.

C++ IntelliCodeC++ IntelliCode

在 Visual Studio 2019 中,IntelliCode 可用作 C++ 桌面开发工作负载中的可选组件 。In Visual Studio 2019, IntelliCode is available as an optional component in the C++ Desktop Development workload. 要确保 IntelliCode 对 C++ 可用,请转到“工具” > “选项” > “IntelliCode” > “常规”并将“C++ 基础模型”设置为“启用” 。To make sure that IntelliCode is active for C++, go to Tools > Options > IntelliCode > General and set C++ base model to Enabled.

在 Visual Studio 2017 中,IntelliCode 可用作 Visual Studio Marketplace 中的扩展。In Visual Studio 2017, IntelliCode is available as an extension in the Visual Studio Marketplace.

预测 IntelliSense(试验性)Predictive IntelliSense (Experimental)

“预测 IntelliSense”是一项试验性功能,它使用上下文感知来限制 IntelliSense 下拉列表中显示的结果数 。Predictive IntelliSense is an experimental feature that uses contextual awareness to limit the number of results displayed in the IntelliSense dropdown list. 该算法会应用类型匹配,以便仅显示与预期类型匹配的结果。The algorithm applies type matching so that it shows only those results that match the expected type. 在最简单的情况下,如果键入 int x = 并调用 IntelliSense 下拉列表,则只会看到整数或返回整数的函数。In the simplest case, if you type int x = and invoke the IntelliSense dropdown, you will see only integers or functions returning integers. 默认情况下,此功能处于关闭状态,因为它仍处于开发阶段。This feature is off by default because it is still in development. 它最适合用于全局符号;尚不支持成员函数。It works best with global symbols; member functions are not yet supported. 可以通过在“快速启动”中键入“预测”或转到“工具” > “选项” > ”文本编辑器” > ”C/C++” > “试验性” > “启用预测 IntelliSense”来将其打开 。You can turn it on by typing "Predictive" in Quick Launch or by going to Tools > Options > Text Editor > C/C++ > Experimental > Enable Predictive IntelliSense.

要替代“预测 IntelliSense”并显示较长的列表,请按 Ctrl + J 。如果已启用“预测 IntelliSense”,则调用 Ctrl + J 将删除预测筛选器 。To override Predictive IntelliSense and show the longer list, press Ctrl + J. If Predictive IntelliSense is on, invoking Ctrl + J removes the Predictive filter. 再次按 Ctrl + J 会从相关成员列表结果中删除辅助功能筛选器 。Pressing Ctrl + J again removes the accessibility filter from Member List results where relevant. IntelliSense 下拉列表下的 ([+]) 按钮与 Ctrl + J 具有相同功能 。将鼠标悬停在该按钮上,可查看有关要显示的内容的工具提示信息。The ([+]) button under the IntelliSense dropdown list does the same thing as Ctrl + J. Hover over the button to see tooltip information about what is being shown.

C++ 预测 IntelliSenseC++ Predictive IntelliSense

上面的屏幕截图显示了下拉列表下的几个按钮。The preceding screenshot shows several buttons under the dropdown list. 它们为不同类型的结果启用了 IntelliSense 筛选器:These enable IntelliSense Filters for different kinds of results:

  • 变量和常量Variables and Constants
  • 函数Functions
  • 类型Types
  • Macros
  • 枚举Enums
  • 命名空间Namespaces

仅当某一按钮与当前 IntelliSense 会话相关时,才会显示该按钮。A button is displayed only if it is relevant to your current IntelliSense session. 通常不会同时看到所有按钮。You typically do not see all the buttons at the same time.

模板 IntelliSenseTemplate IntelliSense

当脱字号位于模板定义中时,系统会显示“模板栏”,让你能够为 IntelliSense 提供示例模板参数 。When the caret is inside a template definition, a Template Bar appears, which enables you to provide sample template arguments for IntelliSense.

C++ 模板 IntelliSense 显示现有实例化C++ Template IntelliSense Show Existing Instantiations

单击 图标,展开/折叠“模板栏” 。Click the icon to expand/collapse the Template Bar. 单击铅笔图标或双击“模板栏”,打开“编辑”窗口 。Click the pencil icon or double-click the Template Bar to open the Edit window.

C++ 模板 IntelliSenseC++ Template IntelliSense

在窗口中进行的编辑将直接应用于源代码,以便可以实时查看效果。Edits that you make in the window are applied directly to the source code, so that you can see the effects in real time.

模板栏可以根据代码中的实例化自动填充候选项。The Template Bar can auto-populate candidates based on instantiations in your code. 单击“添加所有现有实例化”,查看已用于在整个代码库中实例化模板的所有实际参数的列表 。Click on Add All Existing Instantiations to see a list of all concrete arguments that have been used to instantiate the template throughout your code base.

C++ 模板 IntelliSense 结果列表C++ Template IntelliSense Results List

编辑器底部的窗口显示了每个实例化的位置及其参数。A window at the bottom of the editor shows where each instantiation was found, and what its arguments were.

C++ 模板 IntelliSense 实例化映射C++ Template IntelliSense Instantiation Map

“模板栏”信息被视为特定于用户 。Template Bar information is treated as user-specific. 该信息存储在 .vs 文件夹中,并且不提交给源代码管理。It is stored in the .vs folder and is not committed to source control.

错误波浪线和快速修复Error squiggles and quick fixes

如果编辑器检测到代码出现问题,它将在问题下方添加彩色波浪线。If the editor detects problems with your code, it will add colored squiggles under the problem. 红色波浪线表示无法编译的代码。Red squiggles indicate code that won't compile. 绿色波浪线表示仍可能很严重的其他类型的问题。Green squiggles indicate other kinds of problems that might still be potentially serious. 可以打开“错误列表”窗口,获取有关问题的详细信息 。You can open the Error List window to get more information about the problems.

对于某些类型的错误以及常见的编码模式,编辑器将以灯泡(在将鼠标悬停在波浪线上时出现)的形式提供“快速修复” 。For some kinds of errors, as well as common coding patterns, the editor will offer a Quick Fix in the form of a light bulb that appears when you hover over the squiggle. 单击向下箭头查看建议。Click the down arrow to see the suggestions.

以下示例中声明了 vector 但未找到定义,因此编辑器会包含必需的头文件:In the following example, a vector was declared but no definition was found, so the editor offers to include the necessary header file:

C++ 快速修复C++ quick fix

编辑器还提供了快速修复,以获得一些重构机会。The editor also offers Quick Fixes for some refactoring opportunities. 例如,如果在头文件中声明一个类,Visual Studio 将会在单独的 .cpp 文件中为其创建定义。For example, if you declare a class in a header file, Visual Studio will offer to create a definition for it in a separate .cpp file.

C++ 快速修复C++ quick fix

Change trackingChange tracking

每次对文件进行更改时,左侧都将出现一个黄色栏,表示所做的更改未保存。Whenever you make a change to a file, a yellow bar appears on the left to indicate that unsaved changes were made. 保存文件时,该栏将变为绿色。When you save the file, the bar turns green. 只要文档在编辑器中打开,就会保留绿色和黄色栏。The green and yellow bars are preserved as long as the document is open in the editor. 它们代表自上次打开文档以来所做的更改。They represent the changes that were made since you last opened the document.

C++ 更改跟踪C++ change tracking

移动代码Move code

可以通过选中代码,按住 Alt 并按向上/向下箭头键来上下移动代码行 。You can move lines of code up and down by selecting them, holding down Alt, and pressing the Up/Down arrow keys.

插入代码片段Insert snippets

代码片段是一段预定义的源代码。A snippet is a predefined piece of source code. 在单个点上或在选定文本上右键单击以插入代码片段或用代码片段环绕选定文本。Right-click on a single point or on selected text to either insert a snippet or surround the selected text with the snippet. 下图显示用 for 循环环绕选定语句的三个步骤。The following illustration shows the three steps to surround a selected statement with a for loop. 最终图像中的黄色突出显示是使用 tab 键访问的可编辑字段。The yellow highlights in the final image are editable fields that you access with the tab key. 有关详细信息,请参阅代码片段For more information, see Code Snippets.

C++ 插入代码片段下拉列表C++ Insert Snippet Drop-down

添加类Add Class

在“项目”菜单或“解决方案资源管理器”的上下文菜单中添加新类 :Add a new class from the Project menu, or from the context menu in Solution Explorer:

在 C++ 中添加新类Add New Class in C++

也可使用类向导来修改或检查现有类。You can also use Class Wizard to modify or examine an existing class.

C++ 类向导

有关详细信息,请参阅用代码向导添加功能 (C++)For more information, see Adding Functionality with Code Wizards (C++).

重构Refactoring

可在“快速操作”上下文菜单下,或者通过单击编辑器中的灯泡使用重构。Refactorings are available under the Quick Action context menu, or by clicking on a light bulb in the editor. 有的也可从“编辑”>“重构”菜单访问 。Some are also found in the Edit > Refactor menu. 这些功能包括:These features include:

使用 ClangFormat 和 EditorConfig 强制执行代码样式Code style enforcement with ClangFormat and EditorConfig

Visual Studio 2017 及更高版本附带对 ClangFormat(一种基于 Clang/LLVM 的常用 C++ 代码格式化实用工具)的内置支持。Visual Studio 2017 and later comes with built-in support for ClangFormat, a popular code-formatting utility for C++ based on Clang/LLVM. 快速启动中键入“ClangFormat”,将其设置为使用以下某种常用格式:Type "ClangFormat" into Quick Launch to set it to use one of these common formats:

  • LLVMLLVM
  • GoogleGoogle
  • ChromiumChromium
  • MozillaMozilla
  • WebKitWebKit
  • Visual StudioVisual Studio

还可以提供自己的 .clang 格式或 _clang 格式文件,以将自定义规则应用于同一级别或更低级别的所有代码文件。You can also provide your own .clang-format or _clang-format file to apply custom rules to all code files at the same level or below.

这些文件可以通过源代码管理轻松共享,因此可以在整个开发团队中强制执行编码约定。The files are easily shareable via source control, so you can enforce coding conventions across your whole development team.

C++ Clang 格式C++ Clang Format

Visual Studio 2017 及更高版本还支持工作方式类似的 EditorConfigVisual Studio 2017 and later also supports EditorConfig, which works in a similar way. 但是,ClangFormat 的样式选项比 EditorConfig 要多,包括特定于 C++ 的规则。ClangFormat, however, has a more style options than EditorConfig, including rules that are specific to C++. 使用 EditorConfig 创建 .editorconfig 文件,并将其置于代码库的不同文件夹中,以指定这些文件夹及其子文件夹的代码样式 。With EditorConfig, you create .editorconfig files and place them in different folders of your codebase to specify code styles for those folders and their subfolders. .editorconfig 文件会取代父文件夹中的任何其他 .editorconfig 文件,并覆盖通过“工具” > “选项”配置的任何格式设置 。An .editorconfig file supersedes any other .editorconfig files in parent folders and overwrites any formatting settings configured via Tools > Options. 可以为制表符和空格、缩进大小等设置规则。You can set rules for tabs vs. spaces, indent size, and more. 有关详细信息,请参阅使用 EditorConfig 创建可移植的自定义编辑器设置For more information, see Create portable, custom editor settings with EditorConfig.

其他格式设置选项Other formatting options

“快速启动”搜索框中提供了用于查找设置或工具的最快方式 。The Quick Launch search box provides the fastest way to find a setting or tool. 它位于主菜单上。It is located on the main menu. 只需开始键入,自动完成列表即可筛选结果。Just start typing and the auto-completion list will filter the results.

Visual Studio 快速启动Visual Studio Quick Launch

若要设置缩进、括号补全和着色等格式设置选项,请在“快速启动”窗口中键入“C++ 格式设置” 。To set formatting options such as indents, brace completion, and colorization, type "C++ Formatting" into the Quick Launch window.

C++ 格式设置选项

其他格式设置选项位于主菜单中的“编辑” > “高级”下 。Other formatting options are found under Edit > Advanced in the main menu.

C++ 高级编辑选项

启用和配置 C++ 特定编辑功能的选项位于“工具” > “选项” > “文本编辑器” > “C/C++”下 。Options for enabling and configuring C++-specific editing features are located under Tools > Options > Text Editor > C/C++. 选择想要设置的选项之后,在焦点位于对话框上时按 F1 可获取更多帮助 。After choosing which option you want to set, you can get more help by pressing F1 when the dialog is in focus. 如需通用代码格式设置选项,请在“快速启动”中键入 Editor C++For general code formatting options, type Editor C++ into Quick Launch.

Visual Studio Tools > 选项Visual Studio Tools > Options

文本编辑器 C++ 实验对话框中可找到实验性功能,未来版本的 Visual Studio 中不一定包含这些功能。Experimental features, which may or may not be included in a future version of Visual Studio, are found in the Text Editor C++ Experimental dialog. 在 Visual Studio 2017 及更高版本中,可在此对话框中启用“预测 IntelliSense” 。In Visual Studio 2017 and later you can enable Predictive IntelliSense in this dialog.

请参阅See Also

阅读并理解 C++ 代码Read and understand C++ code
在 Visual Studio 中导航 C++ 代码库Navigate your C++ code base in Visual Studio
使用适用于 C++ 的 Live Share 进行协作Collaborate with Live Share for C++