NULL vs nullptr
C++11中的nullptr也可以用类来表示,这符合C++一切概念用类来表示的惯例
首先C++比C有更强的类型检查,C中的NULL被定义为(void*)0,但是在C++中只能被定义为0,因为在C++中void*不能隐式转换为其他类型。
#include <iostream>
#include <cstdlib>
using namespace std;
class nullptr_t1
{
public:
//定义类型转换操作符,使nullptr_t 可转为任意非类成员指针类型
template<class T>
inline operator T*() const{
cout << "operator T*() const" << endl;
return 0;
}
//重载类型转换操作符,使 nullptr_t 可以转换为类 C 中任意的指针类型(数据成员指针/函数成员指针)
//对类中数据成员的指针,T 将被推导为数据成员的类型
//eg: int (X::*); 此时 T 为 int,C 为 X
//对类中函数成员的指针,T 将被推导为函数成员的类型
//eg: int (X::*)(int); 此时T 等效于: typedef int (T)(int)
template<class C, class T>
inline operator T C::*() const{
cout << "operator T C::*() const" << endl;
return 0;
}
private:
void operator&() const;
};
const nullptr_t1 nullptr1 = {};
class Test{
public:
void show(int i){
cout << "void show(int)" << endl;
}
int* m_i;
};
void print(int i){
cout << "int" << endl;
}
void print(void* p){
cout << "void*" << endl;
}
#define NULL1 (void *)0
int main(){
print(0);
print(NULL1);
print(nullptr1);
Test t;
t.m_i = nullptr1;
int (Test::* pi) = nullptr1;
void (Test::* p)(int) = nullptr1;
return 0;
}