2.c++函数重载

重载规则
1 函数名相同
2 参数个数不同,参数的类型不同,参数顺序不同
3 返回值类型,不作为重载的标准

#include <iostream>

using namespace std;

void func(int a)
{
	printf("void func(int a)\n");
}

void func(char a)
{
	printf("void func(char a)\n");
}

int main()
{
	int a=0;
	func(a); //void func(int a)
	char b=' ';
	func(b); //void func(char a)			
	return 0;
}

匹配规则
1 严格匹配,找到则调用。
2 通过隐式转换寻求一个匹配,找到则调用。

#include <iostream>
using namespace std;

void print(double a)
{
	cout << a << endl;
}

void print(int a)
{
	cout << a << endl;
}

int main()
{
	print(1); // print(int)
	print(1.1); // print(double)
	print('a'); // print(int)
	print(1.11f); // print(double)
	return 0;
}

重载底层实现
C++利用 Name Mangling(命名倾轧)技术,来改变函数名,区分参数不同的同名函数。实现原理:用 v-c- i-f- l- d 表示 void char int float long double及其引用。具体平台,实现有差异。
extern "C"
Name Mangling(命名倾轧) 依据函数声明来进行倾轧的。若声明被倾轧,则调用为倾轧版本,若声明为非倾轧版本,则调用也为非倾轧版本。C/C++的编译都是以文件为单位进行编译的。
C++ 默认所有函数倾轧
若有特殊函数不参与倾轧,则需要使用 extercn “C” 来进行声明。C++ 完全兼容 c 语言,那就面临着,完全兼容 C 的类库。由.c 文件的类库文件中函数名,并没有发生 name mangling 行为,而我们在包含.cpp 文件所对应的.h 文件时,.h 文件要发生 name manling 行为,因而会在链接的时候发生的错误。C++为了避免上述错误的发生,重载了关键字 extern。只需要在避免 name manling 的函数前,加 extern “C” 如有多个,则 extern “C”{}.
运算符重载

#include <iostream>
using namespace std;

struct Comp
{
	float real;
	float image;
};

Comp operator+(Comp one, Comp another)
{
	one.real += another.real;
	one.image += another.image;
	return one;
}

int main()
{
	Comp c1 = { 1,2 };
	Comp c2 = { 3,4 };
	Comp sum = c1 + c2; //operator+(c1,c2);
	cout << sum.real << " " << sum.image << endl; //4 6
	return 0;
}

默认参数
默认参数规则
1 默认的顺序,是从右向左,不能跳跃。
2 函数声明和定义一体时,默认认参数在定义(声明)处。声明在前,定义在后,默
认参数只能在声明处。
3 默认值可以是常量,全局变量,或是一个函数。
4 实参个数 + 默认参数的个数 >= 形参个数

#include <iostream>

using namespace std;

void print(int a, int b = 2, int c = 3);
//void print(int a = 1, int b = 2, int c); //错误
//void print(int a = 1, int b, int c = 3); //错误

//void print(int a=1,int b=2,int c=3) //错误
void print(int a, int b, int c)
{
	cout << "print" << endl;
}

int main()
{
	//print(); //错误
	//print(1); //正确
	print(1, 2, 3); //正确
	return 0;
}

规则冲突(conflict)
一个函数,不能既作重载,又作默认参数的函数。当你少写一个参数时,系统无法确认是重载还是默认参数。当两者要实现同样的功能时,优先选用默认参数。

#include <iostream>
using namespace std;

void print(int a)
{

}

void print(int a, int b = 10)
{

}

int main()
{
	print(10); //“print”: 对重载函数的调用不明确
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值