功能#
介绍#
函数是 C++ 编程的基本组成部分,它将代码片段打包成可重用、高效的代码段,用于执行特定任务。函数可以在一个程序中多次调用,从而简化代码组织,并有助于避免重复代码。函数还能使代码更易于调试。
在 C++ 中,函数必须声明其返回类型、名称和参数。基本语法如下:
用法:
return_type function_name(parameters) {
// Code to execute when the function is called
return result; // Optional, used to return a value
}
功能部件 |
描述 |
---|---|
|
The data type that the function returns ( |
|
函数的名称。 |
|
可选。在调用函数时接受输入值的变量,允许将数据传递到函数中。 |
|
Optional. Let the function send a result back to the caller. If a function has a return type other than |
注意:函数必须始终在调用之前声明,或者必须提供函数原型。
定义和调用函数#
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#
您还可以向函数添加参数,以便传递函数要使用的信息。
// Define a function with a parameter
void named_greeting(char name[]) {
Brain.Screen.print("Hello, %s!", name);
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
named_greeting("Stranger");
}
Functions with Default Arguments#
默认参数是如果函数调用中没有为该参数提供值,则采用默认值的参数。
// Define a function with a parameter and a default argument
void named_greeting(char name[] = "Stranger") {
Brain.Screen.print("Hello, %s!", name);
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Use the default argument
named_greeting();
Brain.Screen.newLine();
// Change the parameter to a different name
named_greeting("IQ");
}
Return Values from Functions#
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 times_two(int number) {
return number * 2;
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Display the return value
Brain.Screen.print("%d", times_two(2));
}