当前位置: 首页> 教育> 幼教 > 甘肃兰州是不是封城了_百度推广费_什么叫网络市场营销_清远头条新闻

甘肃兰州是不是封城了_百度推广费_什么叫网络市场营销_清远头条新闻

时间:2025/7/22 15:11:38来源:https://blog.csdn.net/hefaxiang/article/details/146138897 浏览次数:0次
甘肃兰州是不是封城了_百度推广费_什么叫网络市场营销_清远头条新闻

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;
}

结果:

关键字:甘肃兰州是不是封城了_百度推广费_什么叫网络市场营销_清远头条新闻

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: