函数#

介绍#

函数是 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

The data type that the function returns, some common options are:

  • void — Returns nothing
  • int — Returns an integer value
  • double — Returns a floating-point number
  • bool — Returns true or false
  • char — Returns a single character
  • const char* — Returns a text string
  • user-defined types — Returns a struct or class object

function_name

函数名称。

parameters

Optional. A comma-separated list of typed parameters written as type name, where type specifies the data type of the parameter and name is the identifier used to access that value inside the function. Parameters receive input values when the function is called.

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++ 中,代码是从上到下读取的。这意味着函数必须先被编译器识别,才能被调用。

A function prototype lets you use a function before writing its full code. This allows you to keep main() near the top of your program while placing function definitions later, where they are easier to organize and read.

Without a prototype, you would have to define every function above main(), which can make projects harder to follow as they grow.

// 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#

If a function does not require input, you can define it without parameters. Use void as the return type if the function doesn’t return a value.

// 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#

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

Note: Text can be passed using C-style strings (const char*) or C++ strings (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");
}

返回值#

Functions can send data back to the caller using the return keyword. This allows you to capture and use the output in your project.

// 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));
}

引用传递#

默认情况下,C++ 按值传递函数参数,这意味着函数接收到的是Variables.md变量的副本。函数内部所做的更改不会影响原始值。

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

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

To allow a function to modify the original variable, parameters can be passed by reference using the & symbol.

// 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);
}