#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 类() 运行上述代码测试一下吧