What & How & Why

差别

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

到此差别页面的链接

两侧同时换到之前的修订记录前一修订版
后一修订版
前一修订版
cs:programming:cpp:courses:cpp_basic_deep:chpt_6 [2024/10/05 02:55] – [函数指针] codingharecs:programming:cpp:courses:cpp_basic_deep:chpt_6 [2024/10/05 03:17] (当前版本) – [函数指针作为返回值] codinghare
行 528: 行 528:
 </code> </code>
 ==函数指针== ==函数指针==
- 
 <code cpp> <code cpp>
 #include <iostream> #include <iostream>
行 568: 行 567:
  
 } }
 +</code>
 +==函数的退化==
 +  * 赋值时,函数类型会退化为函数指针类型
 +<code cpp>
 +// fun 是 int(*)(int)
 + auto fun = inc;
 +</code>
 +===函数指针与重载===
 +  * 重载时尽量显式的使用函数类型
 +<code cpp>
 +void fun(int) { std::cout << "single para;\n"; }
 +void fun(int, int) {std::cout << "double para;\n"; }
  
 +int main(int argc, char const *argv[])
 +{
 +    // 无法通过 auto 来推断 fun 的类型
 +    // fun 在此处包含了两个不同类型的函数
 +    // auto 无法确定选择哪一个 fun
 +    auto x = fun;
 +
 +    // 需要显式的指定类型
 +    using K = void(int);
 +    K* x = fun; //int(int) type
 +    return 0;
 +}
 +</code>
 +===函数指针作为返回值===
 +  * 可以使用函数作为返回值
 +  * 函数无法复制,返回的类型是函数指针
 +<code cpp>
 +int inc(int x) { return x + 1; }
 +int dec(int x) { return x - 1; }
 +
 +auto fun(bool condition, int x)
 +{
 +    // 返回的实际上是函数的指针
 +    return condition ? inc(x) : dec(x);
 +}
 +
 +int main(int argc, char const *argv[])
 +{
 +
 +    std::cout << fun(true,1) << std::endl;
 +    return 0;
 +}
 </code> </code>