# 提取函数

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com/zh-cn/help/clion/llms.txt).

> **TL;DR**
> `重构 | 提取/引入 | 方法`
>
>
>
> `Ctrl+Alt+M` (Windows), `⌘ ⌥ M` (macOS), `⌘ ⌥ M` (IntelliJ IDEA Classic (macOS)), `⌘ ⌥ M` (macOS System Shortcuts), `Ctrl+Alt+M` (XWin), `Ctrl+Alt+M` (GNOME), `Ctrl+Alt+M` (KDE), `Ctrl+Alt+M` (Emacs), `Ctrl+Alt+M` (Sublime Text), `⌘ ⌥ M` (Sublime Text (macOS)), `⌘ ⌃ ⌥ M` (Xcode), `Ctrl+R, M` (Visual Studio), `⌘ R, M` (Visual Studio (macOS)), `Ctrl+Alt+M` (ReSharper), `⌘ ⌥ M` (ReSharper (macOS)), `Ctrl+Alt+M` (QtCreator), `⌘ ⌥ M` (QtCreator (macOS)), `Alt+Shift+M` (NetBeans), `Alt+Shift+M` (Eclipse), `⌘ ⌥ M` (Eclipse (macOS))

调用  提取函数  重构时，CLion 会分析选定的代码块，并检测作为选定代码段输入的变量以及作为其输出的变量。

检测到的输出变量将用作提取函数的返回值。

Procedure: 提取函数

1. 在编辑器中，选择要转换为函数的代码块。

> **Tip:**
> 用于形成方法的代码片段不一定必须是一组语句。 它也可能是代码中使用的一个表达式。

2. 从主菜单或选定内容的上下文菜单中，选择  `重构 | 提取/引入 | 方法` 或按 `Ctrl+Alt+M` (Windows), `⌘ ⌥ M` (macOS), `⌘ ⌥ M` (IntelliJ IDEA Classic (macOS)), `⌘ ⌥ M` (macOS System Shortcuts), `Ctrl+Alt+M` (XWin), `Ctrl+Alt+M` (GNOME), `Ctrl+Alt+M` (KDE), `Ctrl+Alt+M` (Emacs), `Ctrl+Alt+M` (Sublime Text), `⌘ ⌥ M` (Sublime Text (macOS)), `⌘ ⌃ ⌥ M` (Xcode), `Ctrl+R, M` (Visual Studio), `⌘ R, M` (Visual Studio (macOS)), `Ctrl+Alt+M` (ReSharper), `⌘ ⌥ M` (ReSharper (macOS)), `Ctrl+Alt+M` (QtCreator), `⌘ ⌥ M` (QtCreator (macOS)), `Alt+Shift+M` (NetBeans), `Alt+Shift+M` (Eclipse), `⌘ ⌥ M` (Eclipse (macOS))。

3. 在打开的   提取函数  对话框中，指定新函数的名称、返回类型和其他设置。

![提取方法对话框](https://resources.jetbrains.com/help/img/idea/2026.3/cl_extractMethodDialog.png)

如果该函数尚未声明，请选择声明位置：当前位置的上方或下方。

在参数窗格中：

* 添加新参数或删除不必要的参数

* 通过点击相应的参数行并输入新名称和类型来重命名参数或/和更改其类型

* 重新排列列表中的参数

* 更改函数的返回类型

可以使用相应的复选框将函数设为  `constexpr`  或  `noexcept` 。

4. 在   签名预览  窗格中检查结果，然后点击   提取  以创建函数。

选定的代码片段将被函数调用替换。

|  调整前  |  调整后  |
| --- | --- |
|     ```CPLUSPLUS int main() {     int x = 15;     int y = 10;      int z = x - y;      return 0; }  ```    |     ```CPLUSPLUS int main() {     int x = 10;     int y = 15;      int z = XSubY(x,y);      return 0; }  void XSubY(int x, int y) { return x - y; }  ```    |

