在 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. 智慧型 篩選會顯示內含子字串符合鍵入內容的所有符號。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設定 C++ IntelliSense 專案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

按一下 <T> 圖示,即可展開/折迭 範本 列。Click the <T> 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:

顯示錯誤波浪線的螢幕擷取畫面,以及編輯器提供的快速修正。Screenshot showing error squiggles and the quick fix that the editor offers.

編輯器也會提供快速檢修以獲取一些重構機會。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.

顯示快速修正的螢幕擷取畫面,其中已醒目提示通道中的 [建立通道路由 Iterator 的定義] 選項。Screenshot showing the quick fix with the Create definition of Channel Route Iterator in channels dot C P P option highlighted.

變更追蹤Change 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-format 或 _clang-format 檔案,將自訂規則套用至相同層級以下的所有程式碼檔案。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 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. > [選項] 設定的格式設定。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++ Formatting"。To set formatting options such as indents, brace completion, and colorization, type "C++ Formatting" into the Quick Launch window.

C++ 格式化選項

您可以在 Edit > 主功能表中的 [編輯 Advanced ] 下找到其他格式化選項。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
使用 Live Share for C++ 進行共同作業Collaborate with Live Share for C++