实现指针的转换运算符 [英] Implement conversion operator for pointer

查看:203
本文介绍了实现指针的转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单,但我找不到解决方案。

The question is simple but i can't find a solution.

class foo
{
public:
    operator int()
    {
        return 5;
    }
};

foo* a = new foo();   
int b = a;

是否可以实现该行为?

推荐答案

你不能。转换运算符需要是类的成员,但 foo * 不是用户定义的类类型,它是一个指针类型(除了 int b =

You can't. Conversion operators need to be members of a class, but foo* is not a user-defined class type, it's a pointer type (besides, int b = *a would work).

你可以做的最好的事情就是使用一个可以进行转换的效用函数。

The best thing you can do is to use an utility function that does the casting.

这篇关于实现指针的转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆