函数#

介绍#

函数是 C++ 编程的基本组成部分,它将代码片段打包成可重用、高效的代码段,用于执行特定任务。函数可以在程序中多次调用,从而简化代码组织,并有助于避免重复代码。此外,函数也使代码更易于调试。

本页涵盖了 C++ 中函数使用的基础知识,包括:

函数结构和语法#

在 C++ 中,函数必须声明,包括返回类型、函数名和参数。基本语法如下:

return_type function_name(parameters) {
  // Code to execute when the function is called
  return result;  // Optional, used to return a value
}

功能部件

描述

return_type

函数返回的数据类型,一些常见选项包括:

  • void — 不返回任何值
  • int — 返回一个整数值
  • double — 返回一个浮点数
  • bool — 返回 true 或 false
  • char — 返回一个字符
  • const char* — 返回一个字符串
  • 用户自定义类型 — 返回一个结构体 struct 或类对象

function_name

函数名称。

parameters

可选参数。参数列表以逗号分隔,格式为 type name,其中 type 指定参数的数据类型, name 是函数内部用于访问该值的标识符。函数调用时,参数会接收输入值。

result

Optional. The value returned by the function. If the function’s return_type is not void, this value must be provided and its type must exactly match the specified return_type.

注意: 函数必须始终在调用之前声明*,否则必须提供函数原型。

功能原型#

在 C++ 中,代码是从上到下读取的。这意味着函数必须先被编译器识别,才能被调用。

函数原型允许你在编写完整代码之前使用该函数。这样,​​你就可以将 main() 放在程序顶部附近,而将函数定义放在后面,这样更容易组织和阅读。

如果没有原型,你就必须定义 main()上面的每个函数,这会使项目在发展过程中更难跟踪。

// The function's prototype
void greeting();

int main() {
  greeting();
}

// Write the function's body after
void greeting() {
  Brain.Screen.print("Hello!");
}

定义和调用函数#

Functions with No Parameters#

如果一个函数不需要输入,你可以定义一个不带参数的函数。如果函数不返回值,则返回类型应使用 void。

// Define a function to display a message
void greeting() {
    Brain.Screen.print("Hello!");
}

int main() {
    // Initializing Robot Configuration. DO NOT REMOVE!
    vexcodeInit();
    // Call the function to display the message
    greeting();
}

Functions with Parameters#

你还可以向函数添加参数,从而将信息传递给函数使用。

注意: 可以使用 C 风格的字符串(const char*)或 C++ 字符串(std::string )传递文本。

// Define a function with a parameter
void namedGreeting(const char* name) {
    Brain.Screen.print("Hello, %s!", name);
}

int main() {
    // Initializing Robot Configuration. DO NOT REMOVE!
    vexcodeInit();
    namedGreeting("Stranger");
}

返回值#

函数可以使用 return 关键字将数据返回给调用者。这样,您就可以捕获输出并在项目中使用它们。

// Define a function that multiplies numbers by 2
int timesTwo(int number) {
    return number * 2;
}

int main() {
    // Initializing Robot Configuration. DO NOT REMOVE!
    vexcodeInit();
    // Display the return value
    Brain.Screen.print("%d", timesTwo(2));
}

引用传递#

By default, C++ passes function parameters by value, meaning the function receives a copy of the original variable. Changes made inside the function do not affect the original value.

// Add 1 to the number
void addOne(int number) {
  number++;
}

int main() {
  int value = 5;
  addOne(value);
  // "value" will still be 5
}

要允许函数修改原始变量,可以使用 & 符号按引用传递参数。

// Add 1 to the number
void addOne(int& number) {
  number++;
}

int main() {
  int value = 5;
  addOne(value);
  // "value" will now be 6
}

按引用传递允许函数更新在函数外部定义的 variables 而不返回值。

回调函数#

回调函数是指被传递给另一个函数并在特定事件发生时自动调用的函数。

回调函数通常用于按钮按下或传感器更新等事件。

当事件发生时,项目会自动为你调用该函数,而无需你手动调用。

void onPressed() {
  Brain.Screen.print("Screen pressed!");
}

// Call onPressed whenever the screen is pressed
int main() {
  vexcodeInit();
  Brain.Screen.pressed(onPressed);
}

Callback Signatures#

每个回调函数都必须遵循特定的签名,该签名定义了:

  • 返回类型

  • 参数数量

  • 参数类型

所需的签名由 API 确定。回调函数必须与此签名完全匹配。

// This callback function cannot include any parameters
void callback(void);

// This callback function includes four parameters
void callback(axisType axis, double x, double y, double z);

参数名称具有描述性,可以有所不同,但返回类型、参数顺序和参数类型必须完全匹配。

带有默认参数的函数#

函数可以为一个或多个参数定义默认值。当调用函数时未为某个参数提供值时,将使用默认参数。

默认参数规则:

  • 默认参数必须是函数定义中的最后一个参数。

  • 一旦某个参数有了默认值,它之后的所有参数也都必须有默认值。

  • 如果一个函数在其原型中指定了默认参数,则这些默认值不能在函数定义中再次指定。

// Required parameter first, default parameter last
void greeting(const char* name, int repeatCount = 1) {

    for (int i = 0; i < repeatCount; i++) {
        Brain.Screen.print("Hello, %s!", name);
        Brain.Screen.newLine();
    }
}

int main() {
    vexcodeInit();

    // Say what name to greet (V5) and
    // use default value for repeatCount (1)
    greeting("V5");

    Brain.Screen.newLine();

    // Overrides the default value to 3
    greeting("V5", 3);
}