c++重载隐转

#include <studio.h>

class test

{

 int * t;

char c;

public:

 

test(const char g)

{

  c=g;

  t = new int;

  *t = c;

  printf("构造函数 *t = %d,c = %c,t=%p\n",*t,c,(void*)t);

}

 

operator int*()

{

 

 printf("隐转载");

 return t;

}

 

~test()

{

  delete t;

  printf("\n析构函数");

}

};

 

 

int main()

{

  int * it = test('a');

  printf("\n%d",*it);

 printf("\n%p",(void*)it);

return 0;

}

上述我们创造了一个  test 类  类里面使用operator运算符  重载了  int *()  什么意思呢  

operator int*() 函数的意思其实就是强制转换变成了隐转模式

相当于

int * it = (int *) test('a');

这是一个test的临时对象 直接调用构造函数  本来是不推荐这么用的 因为他的作用域只有这一行  没有test类型对象接受的话  

我们通过 operator int*() 定义了 test 对象 强转int*时变成隐式转换   返回了 t 的类成员  

重载转换函数时  不需要写返回值类型 不过要用返回值

直接写  operator 类()   运行上述代码测试一下吧

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值