codecamp

C++ 函数重载

学习C++ - C++函数重载

函数多态性(也称为函数重载)允许我们使用不同数量的参数来调用相同的函数。

函数重载可以创建具有相同名称的多个函数。

多态性意味着具有许多形式。

函数重载的关键是函数的参数列表,也称为函数签名。

如果两个函数以相同的顺序使用相同数量和类型的参数,则它们具有相同的签名。变量名称并不重要。

只要函数具有不同的签名,C++就可以使用相同的名称定义两个函数。

参数的数量或参数的类型,或两者都有所不同。

例子

例如,您可以使用以下原型定义一组print()函数:

void print(const char * str, int width);  // #1 
void print(double d, int width);          // #2 
void print(long l, int width);            // #3 
void print(int i, int width);             // #4 
void print(const char *str);              // #5 

当您使用print()函数时,编译器会将您的使用与具有相同签名的原型相匹配:

print("a", 15);         // use #1 
print("a");             // use #5 
print(2020.0, 11);      // use #2 
print(2020, 12);        // use #4 
print(2020L, 15);       // use #3 

例子


// Overloaded functions. 
#include <iostream> 
using namespace std; 

// function square for int values 
int square( int x ) 
{ 
    cout << "square of integer " << x << " is "; 
    return x * x; 
} // end function square with int argument 

// function square for double values 
double square( double y ) 
{ 
    cout << "square of double " << y << " is "; 
    return y * y; 
} // end function square with double argument 

int main() 
{ 
    cout << square( 7 ); // calls int version 
    cout << endl; 
    cout << square( 7.5 ); // calls double version 
    cout << endl; 
}

上面的代码生成以下结果。

注意

以下签名不能共存。

double cube(double x); 
double cube(double & x); 

函数匹配过程确定了常量和非常量变量之间的区别如下。

void d(char * bits);          // overloaded 
void d(const char *cbits);   // overloaded 

函数返回类型不是函数签名的一部分。

例如,以下两个声明是不兼容的:

  long g(int n, float m);    // same signatures, 
double g(int n, float m);    // hence not allowed 


C++ 函数默认参数
C++ 函数模板
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }