开发者

Implement conversion operator for pointer

开发者 https://www.devze.com 2023-03-22 06:23 出处:网络
The question is simple but i can\'t find a solution. class foo { public: operator int() { return 5; } }; foo* a = new foo();

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

精彩评论

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