模拟nullptr的实现

/*

C++11,其中有一个是新的关键字nullptr

如果我们的编译器是支持nullptr的话,那么我们应该直接使用nullptr来替代NULL的宏定义。正常使用过程中他们是完全等价的。


*/


#include  "stdafx.h"

#include <iostream>
#include <type_traits>
 
using  namespace   std;
 

class  A
{
public:
double  a;
};




void f(char* c)
{
cout << "invoke f(char* c)" << endl;
}


void f(int i)
{
cout << "invoke f(int)" << endl;
}


void  test(double A::*   p)



A  a1;
double  a= a1.*p; //p正确的调用方式


cout << "invoke   test" << endl;
}




// 模拟nullptr的实现
class my_nullptr_tt
{
public:
template<class _Tx>
operator _Tx*() const
{
cout << "自动推导类型" << typeid(_Tx *).name() << endl;
return 0;
}


template<class _Tx, class _Ty>
operator _Ty   _Tx::* () const   // 一个指向_Tx类中_Ty类型成员变量的指针
{
cout << "自动推导类型_Tx   " << typeid(_Tx).name() << "     _Ty   " << typeid(_Ty).name() << endl;


return 0;
}


private:
void operator& () const // 不允许取地址
{}
};


const  my_nullptr_tt   my_nullptr;




int main()
{
f(0);


f(NULL); //  编译器首先解释它是一个整型常量,其次是一个无类型指针(void*)。
/*
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
*/


f((char*)0);
f(nullptr);
test(nullptr);




//模仿
f(my_nullptr);
test(my_nullptr);




return EXIT_SUCCESS;
}



Created  by  黄强


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值