blog:cpp:basic_const

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录 前一修订版
blog:cpp:basic_const [2022/04/23 22:34] – [constexpr 和常量表达式] caodanblog:cpp:basic_const [2022/04/23 22:43] (当前版本) – [constexpr 和常量表达式] caodan
行 79: 行 79:
 const int max_files = 20; const int max_files = 20;
 const int limit = max_files + 1; const int limit = max_files + 1;
 +```
 +
 +但是在一个复杂的系统中,很难分辨一个出是指是不是常量表达式。
 +
 +c++11 规定,允许将变量声明为constexpr 类型,以便编译器来验证变量的值是否是一个常量表达式, 例如:
 +
 +```
 +constexpr int mf = 20;
 +constexpr int limit = mf + 1;
 +constexpr int sz = size();       // 只有当size() 是一个constexpr函数时,这才是一条正确的声明语句。
 +```
 +
 +对constexpr函数的基本要求:
 +
 +1. 常量表达式函数体内只能有一条语句,并且是return语句
 +2. return语句中,不能使用非常量表达式的变量、函数,且return的表达式也要是常量表达式。
 +
 +例:
 +```
 +constexpr int func() {
 +    return 10;
 +}
 ``` ```
  • blog/cpp/basic_const.txt
  • 最后更改: 2022/04/23 22:43
  • caodan