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();
精彩评论