2

c++核心编程--函数的重载

 2 years ago
source link: https://blog.51cto.com/u_15172160/5116219
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

c++核心编程--函数的重载

原创

1.1函数重载概述

c++核心编程--函数的重载_函数重载的条件

作用​:函数可以相同,提高复用性

函数重载必须满足的条件​:

  • 1​.同一个作用域下
  • 2.​函数名称相同
  • 3.函数​参数类型不同​或者​个数不同​或者​顺序不同

注意​:函数的返回值不可以作为函数重载的条件

完整代码示例:

// 函数重载的条件
//1,在同一个作用域中
//2,相同的返回值类型和函数名
//3,函数的参数个数不同或者参数顺序不同或者参数类型不同
void cunc()
{
cout << "func()函数的重载" << endl;
}

void func(int a)
{
cout << "func(int a)函数的重载" << endl;
}

void fuc(double c)
{
cout << "func(doube c )的调用" << endl;
}

void func(int a,double c)
{
cout << "func(int a,double c)函数的调用" << endl;
}

//函数的返回值类型不能作为函数的重载
//int func(int a,double c)
//{
// cout << "函数int func()的调用" << endl;
// return 22;
//}

int main()
{
//func(3.33);
//func(10,3.11);
//func(210, 20);
//func(10,20);
system("pause");
}

输出结果:c++核心编程--函数的重载_函数重载注意事项_02

注意:函数的返回值类型不能作为函数的重载

int func(int a,double c)
{
cout << "函数int func()的调用" << endl;
return 22;
}

输出会直接报错

c++核心编程--函数的重载_函数重载的条件_03

​总结​:​​函数的重载类似与汉语中的多音字,在不同的环境读不同的音,用不同的参数环境调用不同的功能​​

1.2函数重载的注意事项

  • 引用做为重载条件
  • 函数重载碰到函数默认参数
  • 代码示例:
//函数重载的注意事项
//1、引用作为函数参数
void func(int &a)
{
cout << "函数function(int a)的调用" << endl;
}

void func(const int& a)
{
cout << "函数function(const int a)的调用" << endl;
}

//2、函数重载碰到默认参数
void test(int a)
{
cout << "函数test(int a)的调用" << endl;
}

void test(int a,int b=10)
{
cout << "函数test(int a,int b)的调用" << endl;
}

int main()
{
//int a = 10;
//func(a);//实际参数a变量可读可写,传入函数后走可读可写的函数
//func(10);//实际参数10是常量 若走int &a=10;不合法,引用无效;但能走const int &a=10;

test(10, 20);
//test(10);//错误,两个函数都能被调用。出现二义性。

system("pause");
}
  • 1
  • 1收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK