c++中的NULL和nullptr

版权声明:本文为博主原创文章,欢迎转载,请标明出处。 https://blog.csdn.net/Think88666/article/details/86257615

由于NULL的二义性,在c++11中,出现了nullptr。所以在今后写代码的时候,空指针尽量用nullptr表示吧,原因如下:

#include <iostream>
using namespace std;

void test(int a){
    cout<<"int"<<endl;
}
void test(int *a){
    cout<<"int*"<<endl;
}

void main()
{
    test(NULL);
}

本来我们是想传递一个空指针到test函数中,但是test有两个重载函数,而在c++中NULL本质上就是0,所以运行该程序发现打印结果如下:

也就是出现了二义性。但在执行如下代码时:

#include <iostream>
using namespace std;

void test(int a){
    cout<<"int"<<endl;
}
void test(int *a){
    cout<<"int*"<<endl;
}

void main()
{
    test(nullptr);
}

打印结果为:

完美解决了这个问题。

至于nullptr的模拟实现,代码copy至:   http://www.cnblogs.com/porter/p/3611718.html

const
class nullptr_t
{
public:
    template<class T>
    inline operator T*() const
        { return 0; }

    template<class C, class T>
    inline operator T C::*() const
        { return 0; }
 
private:
    void operator&() const;
} nullptr = {};

猜你喜欢

转载自blog.csdn.net/Think88666/article/details/86257615