开发者

Implement conversion operator for pointer

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;

Is it possible to implement tha开发者_StackOverflow中文版t behavior?


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.


You can, by explicitly calling the operator:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜