由于在C++中NULL定义为0,C++中不能将void *类型的指针隐式转换成其他指针类型,而又为了解决空指针的问题,所以C++中引入0来表示空指针,而又因为NULL不能提醒程序员它是一个整数0而不是一个指向0的空指针,所以又引入了nullptr。
1 实现代码
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 = {};
2 测试代码
using namespace std;
const class mynullptr_t
{
public:
template<class T>
inline operator T*() const
{
cout << "T* is called" << endl;
return 0;
}
template<class C, class T>
inline operator T C::*() const
{
cout << "T C::* is called" << endl;
return 0;
}
private:
void operator&() const;
} mynullptr = {};
class A{
public:
int *a;
};
int main(){
int *p = mynullptr;
int A::*a = mynullptr;
cout << p << endl;
cout << a << endl;
}
输出
T* is called
T C::* is called
00000000
0
3 解析代码
类里面有两个公有函数如下:
template<class T> operator T*() const;
template<class C, class T> operator T C::*() const;
其中template表示模板,意味着,T可以使用户自定义的类型。既然是空指针,那么很多种类型的指针都可以指向它,所以使用了模板。使用了operator关键字,operator表示重载,重载有很多种,在这里此函数为一个隐式转换函数。const表示此函数不修改类的成员变量。
- 第一个函数是为了给普通变量指针赋值为0
- 第二个函数是为了给类的成员指针变量赋予空指针
void operator&() const;
即为将&符号禁用。因为空指针没有引用这一说。
const class mynullptr_t
{
} mynullptr = {};
表示nullptr是一个类常量对象;