📄 inlinefunction.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="css/stdlayout.css" type="text/css">
<link rel="stylesheet" href="css/print.css" type="text/css">
<meta content="text/html; charset=gb2312" http-equiv="content-type">
<title>行内函式(Inline function)</title>
</head>
<body>
<h3><a href="http://caterpillar.onlyfun.net/GossipCN/index.html">From
Gossip@caterpillar</a></h3>
<h1><a href="CppGossip.html">C++
Gossip: 行内函式(Inline function)</a></h1>
在 <a href="FunctionABC.html">函式简介</a> 中的范例,有一个pow2()函式:<br>
<div style="margin-left: 40px;"><span style="font-weight: bold; font-family: Courier New,Courier,monospace;">int pow2(int num) { </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace;">
<span style="font-weight: bold; font-family: Courier New,Courier,monospace;">
return num*num; </span><br style="font-weight: bold; font-family: Courier New,Courier,monospace;">
<span style="font-weight: bold; font-family: Courier New,Courier,monospace;">} </span><br>
</div>
<br>
在呼叫函式时会需要分配记忆空间因而需要额外的资源负担,像pow2()这样的小函式,可以“建议”编译器将之设定为“行内函式”(Inline
function),如果建议被采纳,则该函式会自动在呼叫点展现为程式码,行内函式建议可以直接定义于表头档案中,例如:<br>
<ul>
<li>math.h</li>
</ul>
<pre>inline int pow2(int num) { <br> return num*num; <br>} <br>int pow(int, int);</pre>
<br>
虽然在表头档案中不建议实作函式本体,但行内函式实际上还是在呼叫它的执行点上被展开,所以行内函式并不违反这个规则,配合表头档案,您可以如下实作
pow()函式本体:<br>
<ul>
<li>math.cpp</li>
</ul>
<pre>#include "math.h"<br><br>int pow(int n, int p) {<br> int r = 1; <br><br> for(int i = 0; i < p; i++) <br> r *= n;<br> <br> return r; <br>}</pre>
<br>
至于范例主函式则不变,如下所示:<br>
<ul>
<li>main.cpp</li>
</ul>
<pre>#include <iostream><br>#include "math.h"<br>using namespace std;<br><br>int main() {<br> <br> int num = 0;<br> int power = 0; <br><br> cout << "输入数值:"; <br> cin >> num; <br><br> cout << "输入平方:"; <br> cin >> power; <br><br> cout << num << "平方:" <br> << pow2(num) << endl; <br> cout << num << "的" << power << "次方:" <br> << pow(num, power) <br> << endl; <br><br> return 0;<br>}</pre>
<br>
行内函式只能建议编译器,也就是说建议并不一定会被采纳,这视您的编译器而定,像是使用到goto、static变数、回圈、switch等等,这些编译
器可能不接受行内函式的建议,递回函式也无法在呼叫点展开,一个数千行的函式也不适合在呼叫点展开,如果编译器拒绝将函式展开,它会将该函式视为一般函式
进行编译,inline的建议会被忽略。 <br>
<br>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -