C++编程基础二 09-constexpr函数

 1 // C++函数和类 09-constexpr函数.cpp: 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <string>
 7 #include <climits>
 8 #include <array>
 9 #include <math.h>
10 using namespace std;
11 
12 //constexpr函数:是指能用于常量表达式的函数,即可以在编译时计算其返回值的函数。
13 //常量表达式是指指不会改变并且在编译过程就能得到计算结果的表达式。
14 //注意:
15 //1.函数中只能有一个return语句。
16 //2.返回值必须字面值类型(算数类型、引用、指针属于字面值类型)。
17 //3.参数必须是字面值类型(自定义类、IO库、string类型不属于字面值类型)
18 //4.constexp函数被隐式地指定为内联函数。
19 //5.允许递归。
20 
21 //常量表达式函数
22 constexpr int fact(int n)
23 {
24     return n == 1 ? 1 : n * fact(n - 1);
25 }
26 //常量表达式
27 constexpr int num = 5;
28 int main()
29 {
30     //在编译时期可以计算并返回结果
31     cout << fact(num) << endl;
32     cout << fact(3) << endl;
33 
34     //实参为变量时,在程序运行期间计算并返回结果
35     int i = 8;
36     int res = fact(i);
37     cout << res << endl;
38     return 0;
39 }

猜你喜欢

转载自www.cnblogs.com/uimodel/p/9348592.html