How to declare and define a C++ function?
There are several ways to declare and define functions in C++.
- Function declaration and definition are placed in the same file.
// 函数声明
返回值类型 函数名(参数列表);
// 函数定义
返回值类型 函数名(参数列表) {
// 函数体
}
- Function declaration and definition are separated, with declaration placed in the header file and definition placed in the source file.
// 函数声明
返回值类型 函数名(参数列表);
Source file:
// 函数定义
返回值类型 函数名(参数列表) {
// 函数体
}
- Use default parameters:
// 函数声明
返回值类型 函数名(参数列表 = 默认值);
// 函数定义
返回值类型 函数名(参数列表) {
// 函数体
}
- Utilize function templates.
// 函数声明(函数模板)
template <typename T>
返回值类型 函数名(参数列表);
// 函数定义(函数模板)
template <typename T>
返回值类型 函数名(参数列表) {
// 函数体
}
Important notes:
- The function name can consist of letters, numbers, and underscores, but cannot start with a number.
- The return type can be any valid data type, including primitive data types, custom types, and pointer types.
- The parameter list can contain zero or more parameters, each parameter consists of a parameter type and parameter name, and multiple parameters are separated by commas.
- Function declarations can omit parameter names and only keep parameter types, for example: int add(int, int);.
- If a function does not return a value, the return type should be void.
- If a function has no parameters, the parameter list is empty, for example: void printHello();.
- Function templates allow functions to be defined and used in a generic way, allowing specific types to be specified when called based on actual needs.