第7章、第8章重点介绍函数。

C++函数分两种:

  • 有返回值;
  • 没有返回值。

    2.4.1 有返回值的函数

    例如,标准 C/C++ 库中有个 sqrt() 函数,返回平方根。假设计算6.25的平方根:
    1. x = sqrt(6.25); //返回2.5,并分配给x变量
    表达式 sqrt(6.25) 称为函数调用,被调用的函数称为被调用函数(called-function),谁调用 sqrt() 谁就叫做调用函数(calling function),圆括号中的值叫参数,sqrt() 函数发送回去的值叫函数的返回值(return value)。因此,参数是发送给函数的信息,返回值是从函数中发送回去的值。

不要混淆函数原型和函数定义:

  • 函数原型:只描述函数接口,描述的是发送给函数的信息和返回的信息;
  • 函数定义:包含了函数的具体代码。

    2.4.2 函数变体

    有些语言中,有返回值的函数称为函数(function),没有返回值的函数称为过程(procedure)。但 C/C++ 将这两种变体都称为函数。

    2.4.3 自定义函数(无返回值)

    示例: ```cpp

    include

    void fun1(int); //函数原型

int main() { using namespace std; fun1(3); //调用函数 return 0; };

void fun1(int n) //定义函数 { using namespace std; cout << n << endl; }

  1. <a name="JgBnD"></a>
  2. # 2.4.4 自定义函数(有返回值)
  3. 示例:
  4. ```cpp
  5. #include <iostream>
  6. int fun2(int); //函数原型
  7. int main()
  8. {
  9. using namespace std;
  10. int result = fun2(1);
  11. return 0;
  12. }
  13. int fun2(int n) //函数定义
  14. {
  15. return 10 * n;
  16. }

2.4.5 多函数中使用 using 编译指令

示例:

  1. #include <iostream>
  2. using namespace std; //作用本文件的所有函数中
  3. void fun1(int);
  4. int fun2(int);
  5. int main()
  6. {
  7. //...
  8. return 0;
  9. }
  10. void fun1(int n)
  11. {
  12. //...
  13. }
  14. int fun2(int n)
  15. {
  16. //...
  17. return 10 * n;
  18. }