返回首页 C++ 模板

函数的定义和使用模板

封装逻辑、提高复用——函数声明、定义、调用

函数 定义 调用 返回值 GESP4
#include <bits/stdc++.h>
using namespace std;

// 函数声明(原型)
int add(int a, int b);

// 函数定义
int add(int a, int b) {
    return a + b;
}

// 无返回值
void printLine() {
    cout << "----------" << endl;
}

// 带默认参数
void greet(string name, string msg = "你好") {
    cout << msg << ", " << name << " endl;
}

// 函数重载
int maxValue(int a, int b) { return a > b ? a : b; }
double maxValue(double a, double b) { return a > b ? a : b; }

int main() {
    cout << add(3, 5) << endl;    // 8
    printLine();
    greet("小明");                  // 你好, 小明
    greet("小明", "早上好");        // 早上好, 小明
    cout << maxValue(3, 5) << endl;       // 5
    cout << maxValue(3.14, 2.72) << endl; // 3.14
    return 0;
}

📖 要点说明

⚠️ 常见错误