zoukankan      html  css  js  c++  java
  • 【C++ Primer | 06】 函数

    contexpr函数

    const用于运行期常量,constexpr用于编译期常量

    • [test1.cpp]

     1 #include <iostream>
     2 using namespace std;
     3 
     4 constexpr int screen(int x)               // constexpr
     5 {
     6    return x; 
     7 }
     8 
     9 int main()
    10 {   
    11     const int x = 0;                     // const,是常量表达式,因为值不会发生改变
    12     constexpr int z =  screen(x);        // constexpr
    13     cout << z << endl;
    14     return 0;
    15 }

    • [test2.cpp]

     1 #include <iostream>
     2 using namespace std;
     3 
     4 constexpr int screen(int x)
     5 {
     6    return x; 
     7 }
     8 
     9 int main()
    10 {   
    11     int x = 0;                // 不是常量表达式,因为值会改变
    12     int z =  screen(x);
    13     cout << z <<endl;
    14     return 0;
    15 }


    (1)[test1.cpp] 符合constexpr函数的常规用法,即函数的返回类型以及所有的形参类型必须是字面值类型(字面值类型即编译过程就能得到结果的类型)。此时,如果将 const int x = 0 变为int x = 0 就会报错,因为screen函数的用在一个需要常量表达式的上下文中(constexpr类型的变量必须用常量表达式初始化),编译器在编译的过程中会检查函数的返回值是不是常量表达式,如果不是就会报错。 
    (2)[test2.cpp] 表示constexpr函数可以返回非常量表达式,编译的过程没有报错,原因是screen函数并没有用在一个需要常量表达式的上下文中,编译器正在编译的过程中不会去检查该函数的返回值,也就不会报错。 
    (3)作为补充,需要注意的是constexpr函数必须有return语句。

    • 如果在不需要常量表达式的上下文,如:int z = screen(x);可以不返回常量表达式,此时编译器不会检查函数的结果是否会返回常量表达式。

    • 如果是在需要常量表达式的上下文中,如: constexpr int z = screen(x);那么,constexpr函数必须可以返回常量表达式。此时编译器会去检查函数返回的结果是不是常量表达式,如果不是,就会报错。

    函数指针

    6.7节练习

     1 #include<iostream>
     2 #include<vector>
     3 using namespace std;
     4 
     5 int func1(int a, int b)
     6 {
     7     return a + b;
     8 }
     9 
    10 int func2(int a, int b)
    11 {
    12     return a - b;
    13 }
    14 
    15 int func3(int a, int b)
    16 {
    17     return a * b;
    18 }
    19 
    20 int func4(int a, int b)
    21 {
    22     return a / b;
    23 }
    24 
    25 void computer(int a, int b, int(*p) (int, int))
    26 {
    27     cout << p(a, b) << endl;
    28 }
    29 
    30 int main()
    31 {
    32     int i = 10, j = 5;
    33     decltype(func1) * p1 = func1, *p2 = func2, *p3 = func3, *p4 = func4;
    34     vector<decltype(func1) *> vf = { p1, p2, p3, p4 };
    35     for (auto c : vf)
    36         computer(i, j, c);
    37     system("pause");
    38     return 0;
    39 }
  • 相关阅读:
    【统计学】第七章
    【统计学】第六章
    【统计学】第五章
    【统计学】第四章
    【统计学】第三章
    【统计学】第二章
    MYSQL基础
    股票数据Scrapy爬虫
    Scrapy爬虫基本使用
    Scrapy爬虫框架
  • 原文地址:https://www.cnblogs.com/sunbines/p/9013496.html
Copyright © 2011-2022 走看看