【C++】函数重载与nullptr

1、函数重载

C++支持在同一个作用域中出现同名函数,但是要求这些同名函数的形参不同,可以是形参个数不同或者类型不同。这样C++函数调用就表现出了多态行为,使用更灵活。C语言是不支持同一作用域中出现同名函数的。

代码:

形参类型不同:

#include<iostream>
using namespace std;
//参数类型不同
int Add(int a, int b)
{
	cout << "int Add(int a,int b)" << endl;
	return  a + b;
}
double  Add(double a, double b)
{
	cout << "double  Add(double a,double  b)" << endl;
	return a + b;
}
int main()
{
	Add(5, 10);
	Add(2.0, 2.3);
	return 0;
}

结果:

参数个数不同:

 代码:

//函数重载----参数个数不同:
#include<iostream>
using namespace std;
void  f()
{
	cout << "f()" << endl;
}
void f(int b)
{
	cout << "f(int b)" << endl;
}
int main()
{
	f();
	f(2);
	return 0;
}

结果:

当函数参数是缺省参数时:

代码:

#include<iostream>
using namespace std;
void func()
{
	cout << "func()" << endl;
}
void  func(int a = 0)
{
	cout << "func(int a=0)" << endl;
}
int main()
{
	func();
	return 0;
}

结果:

而当传实参时,就不会报错,因为此时函数调用时,没有歧义.

代码:

#include<iostream>
using namespace std;
void func()
{
	cout << "func()" << endl;
}
void  func(int a = 0)
{
	cout << "func(int a=0)" << endl;
}
int main()
{
	//func();
	func(20);
	return 0;
}

结果:

2、nullptr

NULL实际是宏,在传统的C头文件(stddef.h)中,可以看到以下代码:

#ifdef    NULL
    #ifdef   _cplusplus
         #define   NULL   0
    #else
         #define   NULL((void*)0)
    #endif
#endif

在C语言中,void* 指针可以隐式转换为其它类型的指针。

例如:

test.c文件:
 

代码:

#include<stdio.h>
int main()
{

	void* p1 = NULL;
	int* p2 = p1;//不报错。

	return 0;

}

在cpp文件中,void*指针不可以隐式转换为其他类型的指针,只能显示的转换。

代码:

#include<iostream>
using namespace std;
int main()
{
	void* p2 = NULL;
	int* p3 = p2;

	return 0;
}

结果:

代码:

#include<iostream>
using namespace std;
int main()
{
	void* p2 = NULL;
	int* p3 = (int*)p2;

	return 0;
}

结果:

(1)C++中NULL被定义为字面常量0,而在C中NULL被定义为无类型指针(void*)0的常量。

示例:
.C文件:

.cpp文件:

不论采取何种定义,在使用空值的指针时,都不可避免的会遇到一些麻烦,本想通过f(NULL)调用指针版本的f(int*)函数,但是由于NULL被定义为0,调用了f(int x),因此与程序设计的初衷相悖,而f((void*)NULL)调用会报错。

代码1:

#include<iostream>
using namespace std;
void f(int x)
{
	cout << "f(int x)" << endl;
}
void f(int* ptr)
{
	cout << "f(int *ptr)" << endl;
}
int main()
{
	f(0);
	f(NULL);
	//f((void*)0);

	return 0;
}

结果:

代码2:

#include<iostream>
using namespace std;
void f(int x)
{
	cout << "f(int x)" << endl;
}
void f(int* ptr)
{
	cout << "f(int *ptr)" << endl;
}
int main()
{
	f((void*)0);

	return 0;
}

结果:

(2)C++11中引入nullptr(空指针),nullptr是一个特殊的关键字,nullptr是一中特殊类型的字面常量,它可以转换成任意其他类型的指针类型。使用nullptr定义空指针可以避免类型转换的问题,因为nullptr只能被隐式转换为指针类型,而不能被转换为整数类型。

示例:

#include<iostream>
using namespace std;
void f(int x)
{
	cout << "f(int x)" << endl;
}
void f(int* ptr)
{
	cout << "f(int *ptr)" << endl;
}
int main()
{
	f(nullptr);

	return 0;
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值