本 Wiki 开启了 HTTPS。但由于同 IP 的 Blog 也开启了 HTTPS,因此本站必须要支持 SNI 的浏览器才能浏览。为了兼容一部分浏览器,本站保留了 HTTP 作为兼容。如果您的浏览器支持 SNI,请尽量通过 HTTPS 访问本站,谢谢!
这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版后一修订版 | 前一修订版 | ||
cs:programming:cpp:courses:cpp_basic_deep:chpt_6 [2024/10/05 02:55] – [函数指针] codinghare | cs:programming:cpp:courses:cpp_basic_deep:chpt_6 [2024/10/05 03:17] (当前版本) – [函数指针作为返回值] codinghare | ||
---|---|---|---|
行 528: | 行 528: | ||
</ | </ | ||
==函数指针== | ==函数指针== | ||
- | |||
<code cpp> | <code cpp> | ||
#include < | #include < | ||
行 568: | 行 567: | ||
} | } | ||
+ | </ | ||
+ | ==函数的退化== | ||
+ | * 赋值时,函数类型会退化为函数指针类型 | ||
+ | <code cpp> | ||
+ | // fun 是 int(*)(int) | ||
+ | auto fun = inc; | ||
+ | </ | ||
+ | ===函数指针与重载=== | ||
+ | * 重载时尽量显式的使用函数类型 | ||
+ | <code cpp> | ||
+ | void fun(int) { std::cout << " | ||
+ | void fun(int, int) {std::cout << " | ||
+ | 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 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; | ||
+ | } | ||
</ | </ |