实现指针转换操作符

Implement conversion operator for pointer

本文关键字:操作符 转换 指针 实现      更新时间:2023-10-16

这个问题很简单,但是我找不到解决办法。

class foo
{
public:
    operator int()
    {
        return 5;
    }
};
foo* a = new foo();   
int b = a;

有可能实现这种行为吗?

你不能。转换操作符需要是类的成员,但foo*不是用户定义的类类型,它是指针类型(此外,int b = *a也可以)。

你能做的最好的事情是使用一个实用函数来进行强制转换。

可以,通过显式调用操作符:

foo* a = new foo();
int b = a->operator int();