C++ 复习函数的基本知识

C++ 复习函数的基本知识

  要使用 C++ 函数,必须完成如下工作:

  1. 提供函数定义;

  2. 提供函数原型;

  3. 调用函数。

  例子:

#include <iostream>
using namespace std;
void simple(); // function prototype
int main() {
    cout << "main() will call the simple() function.\n";
    simple();
    cout << "main() is finished with the simple() function.\n";
    return 0;
}
void simple() {
    cout << "I'm but a simple function.\n";
}

  下面是程序的输出:

   执行函数 simple() 时,将暂停执行 main() 中的代码。

1 定义函数

  可将函数分为两类,有返回值和无返回值的。没有返回值的函数被称为 void 函数,通用格式如下:

void function(parameterList) {
    statement(s)
    return;    // 可选
}

  其中,parameterList(参数列表)指定了传递给函数的参数类型和数量。

  例子:

void cheers(int n) {    // 无返回值
    for (int i = 0; i < n; i++)
        std::cout << "Cheers!\n";
}

  将 Cheers! 打印指定次数 (n) 。参数列表 int n 意味着调用函数 cheers() 时,应将一个 int 值作为参数传递给它。

  有返回值的函数将生成一个值,并将它返回给调用函数。这种函数的类型将被声明为返回值的类型,格式如下:

typeName functionName(parameterList) {
    statements
    return value;    // 返回值
}

  对于用返回值的函数,必须使用返回语句。其结果必须是 typeName 类型或可以被转换为 typeName 。

  函数在执行返回语句后结束。如果包含多条返回语句,则函数在执行遇到的第一条返回语句后结束。例如:

int bigger(int a, int b) {
    if (a > b)
        return a;
    else
        return b;
}

  return 后可以写表达式,如:

double cube(double x) {
    return x * x * x;
}

  此函数为计算三次方,例如函数调用 cube(1,2) 将返回 1.728。

猜你喜欢

转载自www.cnblogs.com/dirror/p/12742247.html