Z
ZHANK
编程在线教程C++ 教程函数基础与重载
函数与引用

函数基础与重载

函数定义/声明、返回值、函数重载(同名不同参)

函数基础与重载

C++ 的函数和 C 本质相同,但多了两个强大的特性:函数重载默认实参

学完本章你将: 掌握函数声明/定义、返回值、函数重载。


函数基本形式

cpp
#include <iostream>

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

int main() {
    std::cout << add(3, 4) << "\n";  // 7
    return 0;
}

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

函数重载 —— 同名不同参

cpp
// 同一个函数名,参数不同
void print(int x)    { std::cout << "int: " << x << "\n"; }
void print(double x) { std::cout << "double: " << x << "\n"; }
void print(const std::string &s) { std::cout << "string: " << s << "\n"; }

int main() {
    print(42);            // int: 42
    print(3.14);          // double: 3.14
    print(std::string("hello"));  // string: hello
}

💡 编译器根据参数类型和数量自动选择正确的版本。只看参数,不看返回值。


重载决议的陷阱

cpp
void f(int x)     { }
void f(double x)  { }

f(42);     // ✅ 精确匹配 int
f(3.14f);  // ⚠️ float → double(隐式转换),调用 f(double)
f('a');    // ⚠️ char → int(隐式转换),调用 f(int)