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 = {};
来自维基的代码,但是看不懂,求大佬解释。
Based on your description, I wrote the following code in vs2013 to demonstrate.
Result output
T* is called
T C::* is called
00000000
0
Explanation:
First declare a class (in order to avoid conflicts, I used mynullptr_t) and use the const modification, which means that the variables inside cannot be changed.
At the same time, there are two public functions in the class
Where template<class T> means template, which means that T can make user-defined types. Since it is a null pointer, many types of pointers can point to it, so a template is used. The operator keyword is used, so this function is an implicit conversion function. const means that this function does not modify the member variables of the class. If you are not very clear about this aspect, you can refer to these two blogs: 1. Detailed explanation of c++ templates and 2. Two uses of C++ operator.
Define NULL as 0;The function only does one thing, which is to return 0. Why does it return 0? Because when assigning a value to a pointer, if the pointer = 0, it means that the pointer is a null pointer. The reason is because there is the following definition under the <stdio.h> header file:
If you don’t believe it, you can give it a try
Output:00000000void operator&() const; in private means disabling the & symbol.
The pointer p of int * is assigned a null pointer, and the member pointer of class A is assigned a null pointer.Defined some variables in the main function
Mynullptr is assigned to the value on the left, so implicit type conversion is required at this time. How to convert it. Remember the two functions we wrote in the class? They are implicit conversion functions. Match the template according to the type on the left. Of course, the first one matches T*, so the first implicit conversion function is called, and the result is printed as
. The same second one should call the second implicit conversion function, printing
T* is called
. We know that the address of the null pointer is address 0, so the first one prints 00000000 (the 32-bit system pointer occupies 4 bytes, so there are 8 0s). The second one represents the offset because it is a member pointer, and it is 0 because it is a null pointer.C::T* is called