How to declare and define a C++ function?

There are several ways to declare and define functions in C++.

  1. Function declaration and definition are placed in the same file.
// 函数声明
返回值类型 函数名(参数列表);

// 函数定义
返回值类型 函数名(参数列表) {
    // 函数体
}
  1. Function declaration and definition are separated, with declaration placed in the header file and definition placed in the source file.
// 函数声明
返回值类型 函数名(参数列表);

Source file:

// 函数定义
返回值类型 函数名(参数列表) {
    // 函数体
}
  1. Use default parameters:
// 函数声明
返回值类型 函数名(参数列表 = 默认值);

// 函数定义
返回值类型 函数名(参数列表) {
    // 函数体
}
  1. Utilize function templates.
// 函数声明(函数模板)
template <typename T>
返回值类型 函数名(参数列表);

// 函数定义(函数模板)
template <typename T>
返回值类型 函数名(参数列表) {
    // 函数体
}

Important notes:

  1. The function name can consist of letters, numbers, and underscores, but cannot start with a number.
  2. The return type can be any valid data type, including primitive data types, custom types, and pointer types.
  3. 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.
  4. Function declarations can omit parameter names and only keep parameter types, for example: int add(int, int);.
  5. If a function does not return a value, the return type should be void.
  6. If a function has no parameters, the parameter list is empty, for example: void printHello();.
  7. 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.
bannerAds