“nullpt”是C ++ 11中引入的新概念。
在C ++ 11之前,NULL被定义为:
#define NULL 0
但是在C ++ 11之后,NULL被定义为
#define NULL 空点r
“nullptr”在#include中定义<cstddef> header file.
这意味着在C ++ 11之前,NULL将被转换为整数文字0。因此,对于接受NULL和整数0的重载函数将变得困难。
例如:
#include <iostream>
using namespace std;
//for more C ++ tutorial visit www.ProDeveloperTutorial.com
void fun(int num)
{
cout<<"Int func"<<endl;
}
void fun(char *s)
{
cout<<"Char func"<<endl;
}
int main()
{
fun(NULL);
return 0;
}
输出:
main.cpp: In function ‘int main()’:
main.cpp:26:13: error: call of overloaded ‘fun(NULL)’ is ambiguous
fun(NULL);
^
main.cpp:13:5: note: candidate: int fun(int)
int fun(int num)
^~~
main.cpp:18:5: note: candidate: int fun(char*)
int fun(char *s)
您将收到如上所述的错误。
这意味着将NULL转换为‘0’而且编译器在调用哪个函数方面含糊不清。
因此,为了解决此类问题,从C ++ 11开始,他们引入了“nullptr”.
所以现在当您调用fun(nullptr); char函数将被调用。
例:
#include <iostream>
using namespace std;
//for more C ++ tutorial visit www.ProDeveloperTutorial.com
void fun(int num)
{
cout<<"Int func"<<endl;
}
void fun(char *s)
{
cout<<"Char func"<<endl;
}
int main()
{
fun(nullptr);
return 0;
}
输出:
Char func
“nullptr”可以转换为任何指针或指向成员类型的指针。“nullptr”不能隐式转换或与整数类型比较。
例:
#include <iostream>
using namespace std;
//for more C ++ tutorial visit www.ProDeveloperTutorial.com
int main()
{
int x = NULL; // works
int x1 = 空点r; // error.
return 0;
}
Error:
Main.cpp:10:9: error: cannot initialize a variable of type 'int' with an rvalue of type 'nullptr_t'
int x1 = 空点r; // error.
"空点r" is convertable to bool.
#include
using namespace std;
//for more C ++ tutorial visit www.ProDeveloperTutorial.com
int main()
{
int *ptr = 空点r;
if (ptr)
{
cout << "true"<<endl;
}
else
{
cout << "false"<<endl;
}
return 0;
}
输出:
false
You can also create a 空点r variable as below:
空点r np1, np2;
最后的例子:
#include <iostream>
#include <cstddef>
using namespace std;
//for more C ++ tutorial visit www.ProDeveloperTutorial.com
void fun(int *num)
{
cout<<"Int func"<<endl;
}
void fun(char *s)
{
cout<<"Char func"<<endl;
}
int main()
{
int *ptr = 空点r;
fun(ptr);
char *cptr = 空点r;
fun(cptr);
return 0;
}
输出:
Int func Char func
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |