4.为什么使用nullptr而不是0或者NULL

 1 #include<iostream>
 2 using namespace std;
 3 void test(void *p)
 4 {
 5     cout<<"p is pointer "<<p<<endl;
 6 }
 7 void test(int num)
 8 {
 9     cout<<"num is int "<<num<<endl;
10 }
11 int main(void)
12 {
13 
14     test(NULL);
15     return 0;
16 }

在VS2017中,它将输出num is int,因为宏定义里面NULL等同于0(#define NULL 0(void *)) 即使如此它也仍能给int之类赋值了,而nullptr可以转换为任意类型的指针,如果是nullptr则输出p is pointer,显然这才符合我们的初衷。

猜你喜欢

转载自www.cnblogs.com/Royzzzzz/p/11853009.html