基础语法 - 空指针

引子

  • 早期c++编程中定义空指针我们会使用NULL,如下:
int *p = NULL;
  • 但是在函数重载时会出问题的,示例代码如下:
#include <iostream>
#include <string>

using namespace std;

void func(int* num){
    cout << "this is the ptr function..." << endl;
}

void func(int num){
    cout << "this is the normal function..." << endl;
}

int main(int argc, char** argv){
    func(NULL);
    return 0;
}
  • g++ 4.8.4编译以上程序会直接报错,错误信息如下:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:15:15: error: call of overloaded ‘func(NULL)’ is ambiguous
      func(NULL);
               ^
test.cpp:15:15: note: candidates are:
test.cpp:6:6: note: void func(int*)
 void func(int* num){
      ^
test.cpp:10:6: note: void func(int)
 void func(int num){
      ^

原因

  • NULL的定义
#define NULL (void *)0
  • 编译器编译以上示例代码时,NULL会被直接替换成(void *)0,既可以转成为指针类型也可以转换成int类型,因此结果不确定。

解决

  • c++11重新定义了空指针:nullptr,不能被转换成数字。
  • 如果没有使用到指针类型的函数重载,使用NULL也不会报错,但是为了养成好习惯,使用nullptr。

注意项

  • nullptr 需要c++ 11 支持,编译时需要加上 -std=c++11 例如:
g++ nullptr_test.cpp -std=c++11 -o test
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值