C++的函数参数默认值、函数重载、内联函数特性

1.函数参数默认值:

注意:

有默参数值的必须写在参数最右端。

声明时可加默认值,定义时不建议写默认值(有些编译器能通过,有些不能)

#include<stdlib.h>
#include <iostream>

using namespace std;

void fun(int i=30, int j=20, int k=10)
{
	cout << i << "," << j << "," << k << endl;

}

int main()
{

	fun(4);
	fun(4, 5);
	fun(4,5,6);
  system("pause");
  return 0;


}

 结论:无实参则使用默认值。

2.函数重载 :

在相同作用域内,同名函数,参数个数和参数类型不同,构成函数重载

#include<stdlib.h>
#include <iostream>

using namespace std;

/*第一个fun函数*/
void fun(int i=30, int j=20, int k=10)   // 系统会化成 fun_int_int_int
{
	cout << i << "," << j << "," << k << endl;

}

/*第二个fun函数*/
void fun(double i, double j)            // 系统会化成 fun_double_double
{
	cout << i << "," << j << "," << endl;
}


int main()
{

	fun(4);                  //fun_int_int_int类型的,调用第一个函数
	fun(1.1, 2.2);           //fun_double_double类型的,调用第二个函数
	fun(1.1,2);           //fun_double_int类型的,不存在这个重载函数fun,报错

    system("pause");
    return 0;


}

运行结果:

如果我fun(1,2.2)一个不存在的重载类型呢?

显然这是一个fun_int_double类型的,但是没有这样的重载函数定义,编译器会报错,无法识别是哪种

运行结果:

1>------ 已启动生成: 项目: love, 配置: Debug Win32 ------
1>love.cpp
1>e:\c++\my c++\love\love\love.cpp(20): error C2666: “fun”: 2 个重载有相似的转换
1>e:\c++\my c++\love\love\love.cpp(12): note: 可能是“void fun(double,double)”
1>e:\c++\my c++\love\love\love.cpp(6): note: 或    “void fun(int,int,int)”
1>e:\c++\my c++\love\love\love.cpp(20): note: 尝试匹配参数列表“(double, int)”时
1>已完成生成项目“love.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========


 

猜你喜欢

转载自blog.csdn.net/luoyir1997/article/details/82947497