Skip to content

函数重载 ​

函数重载 允许同一作用域内存在多个同名函数,只要它们的参数列表不同。

基本规则:

  • 函数名相同
  • 参数列表不同(参数个数、类型或顺序不同)
  • 返回类型不影响重载

示例 ​

cpp
// 重载:参数个数不同
void print(int x) {
    std::cout << "int: " << x << std::endl;
}

void print(int x, int y) {
    std::cout << "two ints: " << x << ", " << y << std::endl;
}

// 重载:参数类型不同
void print(double x) {
    std::cout << "double: " << x << std::endl;
}

void print(const std::string &s) {
    std::cout << "string: " << s << std::endl;
}

int main() {
    print(10);          // 调用 print(int)
    print(1.5);         // 调用 print(double)
    print("hello");     // 调用 print(string)
    print(1, 2);        // 调用 print(int, int)
}

注意事项 ​

返回类型不影响重载 ​

cpp
// 错误:这两个函数参数相同,仅返回类型不同
int foo(int x);
double foo(int x);  // 编译错误!

const 参数和重载 ​

cpp
void display(int x);
void display(const int x);  // 错误:参数类型相同

void work(int &x);
void work(const int &x);    // 可以重载

void test(int *p);
void test(const int *p);    // 可以重载
  • 引用传递和指针传递是底层 const:可以重载
  • 值传递是顶层 const:不能重载

默认参数不影响重载 ​

cpp
void calc(int a, int b = 10);
void calc(int a);  // 编译错误!与上面冲突
  • 如果调用 calc(1),编译器不知道选哪个