C++中函数的调用

打印 上一主题 下一主题

主题 842|帖子 842|积分 2526

*************
C++
topic: call functions
*************

Calling functins in a program is everywhere.
Beautiful design is really beautiful. It looks exquisite. It is none of this topic's business. 


Come back to functions. As is mentioned before, the basic struction of function is 
  1. // basic structure of function
  2. 返回类型 函数名 (参数类型 参数名,参数类型 参数名,···)
  3. {
  4.    函数体
  5. }
复制代码
 
So write a code as an example.
  1. #include <iostream>
  2. using namespace std;
  3. int g_c;
  4. void add(int a, int b)
  5. {
  6.     g_c = a + b;
  7. }
  8. int main()
  9. {
  10.     return 0;
  11. }
复制代码
int g_c here is a global variable. In another void function, add function can be called.


case 1: call directly
just use the function name to call the function.
  1. #include <iostream>
  2. using namespace std;
  3. int g_c;
  4. void add(int a, int b)
  5. {
  6.     g_c = a + b;
  7. }
  8. int main()
  9. {
  10.     // 直接调用add函数
  11.     add(13, 38);
  12.     return 0;
  13. }
复制代码


case 2 : use undirectly result after calling the add function.
sometimes it may happen that the resultt after used delaying being called.
  1. #include <iostream>
  2. using namespace std;
  3. int g_c;
  4. void add(int a, int b)
  5. {
  6.     g_c = a + b;
  7. }
  8. void checkResult()
  9. {
  10.     // 检查 g_c 的值
  11.     cout << "Result: " << g_c << endl;
  12. }
  13. int main()
  14. {
  15.     add(13, 38);   // add 被调用,结果存入 g_c
  16.     checkResult(); // 检查 g_c 的值
  17.     return 0;
  18. }
复制代码


case 3 : to provude a g_c interface
  1. #include <iostream>
  2. using namespace std;
  3. int g_c;
  4. void add(int a, int b)
  5. {
  6.     g_c = a + b;
  7. }
  8. void Plus()
  9. {
  10.     add(13, 38); // 调用 add 函数
  11. }
  12. int get_g_c()
  13. {
  14.     return g_c;
  15. }
  16. int main()
  17. {
  18.     Plus(); // 通过 Plus 函数调用 add
  19.     int result = get_g_c(); // 通过 get_g_c 函数获取 g_c 的值
  20.     cout << "g_c = " << g_c << endl; // 输出 g_c 的值
  21.     printf("result = %d\n", result); // 输出 result 的值
  22.     return 0;
  23. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

悠扬随风

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表