ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

C ++ 11 feature: 空点r

前开发者教程 2020年2月26日

“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+章

 

 

 

 

 

 

 

分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的





          <dt id="jervCQ5"><s class="wuFvx8n"></s></dt>
        • <small id="mWHBwEd" class="m4hUtdd"><tfoot id="dDNBHqk"><del id="PMb0FHV" class="PXPqZIv"></del></tfoot></small>