【问题标题】:Implement conversion operator for pointer实现指针的转换运算符
【发布时间】:2011-07-23 20:03:40
【问题描述】:

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

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

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

是否有可能实现该行为?

【问题讨论】:

    标签: c++ operators


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以通过显式调用运算符:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-12
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-27
        • 2012-07-24
        • 1970-01-01
        相关资源
        最近更新 更多